Building an AI meme video generator or template platform for TikTok AI video trends introduces three subtle architectural bottlenecks once real users start rendering and sharing clips across vertical (9:16), square (1:1), and widescreen (16:9) feeds:
- Paying for duplicate inference on aspect-ratio exports: Creators frequently generate a
16:9or4:3template clip and immediately want a9:16TikTok cut or a1:1square feed copy—or a silent version so they can attach trending audio directly inside the social app. Re-running a diffusion video model for those exports wastes compute and changes character consistency. - Idempotency key collisions vs. harmless webhook replays: Append-only credit ledgers rely on deterministic
idempotencyKeystrings (grant_{invoiceId},refund_{jobId}) to ignore duplicate Stripe or worker retries. Yet if a bug ever reuses an existing key for a different user or amount,ON CONFLICT DO NOTHINGsilently drops the operation and leaves callers thinking credits moved. - Killing Next.js edge caching just to render a credit badge: Reading auth cookies inside marketing or template landing pages forces dynamic SSR on every visit, hurting TTFB and breaking
bfcache.
Here are the three concrete TypeScript and ffmpeg patterns we use in production across 93 live templates on SameButMe.
1. Zero-Inference Multi-Aspect & Silent Exports for TikTok AI Video Trends (ffmpeg-static)
In a reference-locked video workflow, we keep video generation silent (generateAudio: false) and mux the template's original audio track afterward so spoken lines or music stay aligned without triggering synthetic audio distortion. Once that primary watermark-free MP4 is finished, creators often need a 9:16, 1:1, or muted derivative.
Instead of calling the video model again, we derive share formats deterministically in Node.js using ffmpeg-static with two clean framing modes:
-
crop: Scales up until the shortest edge covers the target frame, then center-crops withsetsar=1. -
pad(blurred backdrop): Splits the stream (split=2), blurs and slightly dims a cropped background layer (boxblur=20:2,eq=brightness=-0.08), and centers the uncropped foreground clip on top.
import { execFile } from "node:child_process"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import ffmpegStatic from "ffmpeg-static"; const run = promisify(execFile); export type ExportFormat = "16:9" | "9:16" | "1:1"; export type ReframeFit = "crop" | "pad"; export const EXPORT_SIZES: Record<ExportFormat, [number, number]> = { "16:9": [1280, 720], "9:16": [720, 1280], "1:1": [720, 720], }; export function reframeFilter(format: ExportFormat, fit: ReframeFit): string { const [w, h] = EXPORT_SIZES[format]; if (fit === "crop") { return `scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},setsar=1`; } return [ "split=2[bg][fg]", `[bg]scale=${w}:${h}:force_original_aspect_ratio=increase,crop=${w}:${h},boxblur=20:2,eq=brightness=-0.08[bgb]`, `[fg]scale=${w}:${h}:force_original_aspect_ratio=decrease[fgs]`, "[bgb][fgs]overlay=(W-w)/2:(H-h)/2,setsar=1", ].join(";"); } export async function reframeVideo(opts: { video: Uint8Array; format: ExportFormat; fit: ReframeFit; mute: boolean; }): Promise<Buffer> { if (!ffmpegStatic) throw new Error("ffmpeg binary not available"); const dir = await mkdtemp(path.join(tmpdir(), "meme-export-")); try { const inPath = path.join(dir, "in.mp4"); const outPath = path.join(dir, "out.mp4"); await writeFile(inPath, opts.video); await run( ffmpegStatic, [ "-y", "-i", inPath, "-filter_complex", reframeFilter(opts.format, opts.fit), ...(opts.mute ? ["-an"] : ["-map", "0:a?", "-c:a", "copy"]), "-c:v", "libx264", "-preset", "veryfast", "-crf", "20", "-pix_fmt", "yuv420p", "-movflags", "+faststart", outPath, ], { timeout: 120_000 }, ); return await readFile(outPath); } finally { await rm(dir, { recursive: true, force: true }); } } Why the ffmpeg flags matter
-
-map 0:a? -c:a copy: The trailing?preventsffmpegfrom failing if a source clip has no audio stream, whilecopyavoids unnecessary AAC re-encoding when sound is kept. -
-movflags +faststart: Moves themoovatom to the front of the file so mobile browsers and social uploaders start decoding frame 1 immediately without downloading the entire MP4 first. -
setsar=1: Prevents non-square pixel aspect ratios from stretching vertically inside iOS Safari or TikTok's ingest pipeline.
2. Collision-Guarded Credit Ledgers for an AI Meme Generator
In an AI meme generator with credit packs (such as $7.99 for 120 credits, $15 for 250, or $40 for 700) and duration-tiered jobs (60/120, 80/160, 120/240, or 150/300 credits across 480p and 720p), every spend, webhook grant, and failed-job credit return must be idempotent.
A common Drizzle/Postgres bug is treating every onConflictDoNothing empty return as a safe replay. If an application bug accidentally generates a non-unique key (for example, forgetting the resolution or retry suffix), ON CONFLICT DO NOTHING returns [], and the caller assumes the new operation succeeded.
Instead, verify that the existing row matches both userId and amount whenever an insert hits a conflict:
import { eq } from "drizzle-orm"; import { creditTransactions } from "@/db/schema"; type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0]; export async function assertSameOperation( tx: Tx, idempotencyKey: string, userId: string, amount: number, ): Promise<void> { const [existing] = await tx .select({ userId: creditTransactions.userId, amount: creditTransactions.amount, }) .from(creditTransactions) .where(eq(creditTransactions.idempotencyKey, idempotencyKey)) .limit(1); if (!existing || existing.userId !== userId || existing.amount !== amount) { throw new Error( `credits: idempotency key collision on ${idempotencyKey} — existing row belongs to a different operation`, ); } } Combined with row-level SELECT ... FOR UPDATE on the user's balance row before any debit or expiry sweep, this guarantees:
- Replayed Stripe webhooks or duplicate clicks become true no-ops.
- Accidental key reuse across operations fails loudly instead of silently dropping a debit or returning credits to the wrong job.
- Failed or timed-out renders return credits cleanly via a compensating append-only
refundrow (refund_{jobId}) without ever mutating historical rows.
3. Keeping AI Meme Video Generator Pages Prerendered With Deduped Viewer Hydration
When a site serves dozens of template landing pages and a live trending AI video templates index, you want those routes prerendered and edge-cached for fast TTFB and instant bfcache navigation—while still showing the signed-in user's credit balance on the upload form and navbar.
Reading cookies() or headers() in Server Components disables static caching for the entire route. Our fix is a tiny client-side viewer store that deduplicates in-flight fetch("/api/viewer") calls across components on the same page and listens for a custom viewer:changed event whenever a job starts, finishes, or returns credits:
"use client"; import * as React from "react"; type Viewer = { signedIn: boolean; credits: number; }; const SIGNED_OUT: Viewer = { signedIn: false, credits: 0 }; const CHANGED = "viewer:changed"; const inFlight = new Map<number, Promise<Viewer>>(); function fetchViewer(cards: number): Promise<Viewer> { let req = inFlight.get(cards); if (!req) { const url = cards > 0 ? `/api/viewer?cards=${cards}` : "/api/viewer"; req = fetch(url, { cache: "no-store" }) .then((res) => (res.ok ? (res.json() as Promise<Viewer>) : SIGNED_OUT)) .catch(() => SIGNED_OUT) .finally(() => inFlight.delete(cards)); inFlight.set(cards, req); } return req; } export function viewerChanged(): void { window.dispatchEvent(new Event(CHANGED)); } export function useViewer(known?: Viewer, cards = 0): Viewer & { ready: boolean } { const [viewer, setViewer] = React.useState<Viewer | null>(null); const skip = Boolean(known); React.useEffect(() => { if (skip) return; let active = true; const load = () => { void fetchViewer(cards).then((next) => { if (active) setViewer(next); }); }; load(); window.addEventListener(CHANGED, load); return () => { active = false; window.removeEventListener(CHANGED, load); }; }, [skip, cards]); if (known) return { ...known, ready: true }; return viewer ? { ...viewer, ready: true } : { ...SIGNED_OUT, ready: false }; } Practical takeaways for Next.js App Router media apps
- Zero-cookie marketing routes: Keep
/,/trends, and duration-based pricing statically prerendered so crawlers and cold visitors receive cached HTML immediately. - One request per page load: Even if the header, upload card, and recent-renders strip all call
useViewer(), the sharedinFlightmap collapses them into a singleGET /api/viewer. - No signed-out UI flash: Exposing
ready: falsebefore the first fetch resolves lets account badges wait cleanly without flickering between "Sign in" and a credit balance.
