Skip to main content
← All writingKylan Thomson

Generative AI · Latency Engineering

Hiding Generative Video Latency With Predictive Cache Warming

You cannot make a video model faster. You can make sure that by the time anyone asks for a clip, everything except the clip is already done.

Published
Reading time
8 minutes
Project
Pokémon TCG Live Attacks case study

An image-to-video model takes tens of seconds to produce six seconds of clip. That is not a number I can change. In a card game where every attack produces a clip, the only lever is to make sure that when the attack is declared, the video is the only thing left to wait for. Everything else has to be done already.

This is the latency design of Pokémon TCG Live Attacks. It is not one trick. It is a chain of bets, each made at the earliest moment the game has enough information to make it, and each cached so it is never made twice. The chain starts the moment a Pokémon is drawn into a hand, which is typically several turns and a couple of minutes before that Pokémon can attack.

The anatomy of one clip

A clip needs three generative results, from three different models, and they depend on each other in sequence.

  1. Two portraits from an image-edit model (a Nano Banana variant on fal.ai): a battle portrait of the Pokémon, edited from its card art under a fixed composition and lighting contract, and a fainted portrait edited from the battle one so the two share an environment. These are the first and last frames of the clip.
  2. A direction from a Gemini pass that reads the whole card, including the illustration, and writes the choreography: the charge-up, the impact, the camera move, how both names are pronounced. Before it can do that, a separate pass has to read the art and describe what the illustration actually shows, so a creature painted with no arms is not directed to punch.
  3. The clip itself, from a MiniMax image-to-video model, given both frames and a prompt composed from the direction and the engine's resolution of the attack.

Done cold, at the moment of the attack, that chain runs art read, then portraits, then direction, then video, and the configured ceilings alone add up to well over a minute before the video even starts. The portrait wait is capped at twenty seconds on the principle that a clip which opens on the card art after twenty seconds beats one that opens on the portrait after seventy-five. Nobody waits seventy-five seconds for a card game.

  • Read the card art
  • Portraits (image edit)
  • Gemini direction
  • Video generation
WAIT AFTER THE ATTACK IS DECLARED (INDICATIVE, SECONDS)020406080Cold: everything at attack timeRead the card art: ~4 sBattle and fainted portraits: ~20 sBattle and fainted portraitsGemini direction: ~6 sVideo generation: ~45 sVideo generation~75 sWarmed: started when the card was drawnVideo generation: ~45 sVideo generation~45 s
The wait after an attack is declared, cold versus warmed. Segment lengths are indicative, drawn from the code's configured ceilings and stated expectations rather than benchmarks: the art read lands in a few seconds, portraits are capped at twenty, the direction at twenty, and video is “tens of seconds”. Warmed, only the last segment remains.

Bet one: a card in a hand will attack

The earliest useful signal is a Pokémon entering a hand. From that moment it is at least a turn from being played and another from attacking, so the client (in single player) or the server (in online matches) diffs the new card ids after every action and fires a warm request for anything it has not seen. That request kicks off, in parallel, the art read for the illustration, the battle portrait, and a Gemini direction for every attack printed on the card, plus pronunciations for the Pokémon's name and all its attack names.

Pokémon in hand get only the battle portrait, since they cannot be attacked before they are played. Once a Pokémon is in play, the fainted and hurt portraits are chained after the battle one, because they are edited from it. The comment on the server-side trigger states the bet plainly: a Pokémon reaching a hand is turns of real time before any of its attacks can be declared.

export function warmDirections(cardIds: string[], arena: ArenaId | null): void {
  for (const cardId of cardIds) {
    void artReadFor(cardId);                 // the portrait waits for this
    for (const attack of card.attacks) {
      void directionFor(cardId, attack.name, arena);
    }
  }
  void warmPronunciations(names);
}
director.ts: everything the direction needs is started as soon as the card is known.
The warm path An architecture diagram generated by Archify. Hand diff · after every action · Architecture component · turns before any attack · React Hand diff after every action turns before any attack POST /api/portraits · warmDirections · warmPortraits · Cloud Run · Next.js POST /api/portraits warmDirections · warmPortraits Gemini director · art read · direction · names · Architecture component · Google Gemini Gemini director art read · direction · names Image edit · battle, then hurt and fainted · Architecture component Image edit battle, then hurt and fainted Firestore caches · keyed by card + version · Cloud Run · once per Pokémon, ever · Firebase Firestore caches keyed by card + version once per Pokémon, ever Attack predictor · likely attack · hover · CPU replay · Architecture component · React Attack predictor likely attack · hover · CPU replay startGeneration · two cache reads, one request · Cloud Run · Next.js startGeneration two cache reads, one request fal.ai queue · video · CPU clips reused ×3 · Architecture component fal.ai queue video · CPU clips reused ×3 new card ids every printed attack portraits write write prepare(signature) read submit, poll Cloud Run Legend Frontend Backend Database External
The warm path. A card reaching a hand triggers the Gemini reads and the portrait edits, which land in Firestore keyed by card and prompt version. By the time an attack is predicted or declared, starting a clip is two cache reads and one queue request.

Cached forever, keyed by version

None of this would be affordable if it ran per match. It runs once per Pokémon for the life of the app. Portraits are keyed by card, variant, arena, and a prompt version; directions by card, attack name, and a direction version; pronunciations by name rather than by card, so every printing of Charizard says its name the same way. Bumping a version constant regenerates that family and nothing else. There are twelve arenas, picked from the match seed, so the worst case is twelve cached portrait sets per Pokémon, ever.

Every cache is two-tiered: a process-global map that survives hot reloads, in front of the document store, which is a local file in development and Firestore in production. An attack declared turns after its Pokémon was drawn is two cache reads and a video request.

Bet two: the attack the player is about to choose

Warming portraits and directions leaves the video itself, which cannot start until the outcome is known, and the outcome depends on which attack the player picks. Or so it would seem. Three predictors run ahead of the choice.

  • The likely attack. On the player's turn, for each attack the active Pokémon could legally declare, the client previews the resolution and queues a clip for the one that would deal the most damage. The preview reads the same seeded random stream the real declaration will read, so if the attack involves a coin, the clip is built for the flip that will actually happen. It is not a guess at the flip. It is the flip, read early. Attacks whose effect the parser does not simulate are skipped, because their outcome is not fully known.
  • Hover intent. Resting the pointer on an attack for 350 milliseconds, or focusing it with the keyboard, queues that clip too. A player who is reading the attack text is likely to click it.
  • The CPU's entire turn. The AI is a pure function of the board and every draw is seeded, so the moment the CPU's turn begins the client replays that whole turn in memory, silently, and the instant the predicted action is an attack it queues the clip. The real declaration arrives several seconds later, after the think delay and each preceding action's own pause, and finds its clip already generating.

A prepared clip is claimed only on an exact match. The claim key is a signature over the resolution: attacker, defender, attack name, applied damage, knockout certainty, conditions inflicted, self-damage, bench damage, and the defender's remaining health. If the player picks a different attack, or plays a card first that changes the damage, the prepared clip does not match and is wasted. That cost is real and it still counts against the player's budget. It is the price of the bet, and the bet pays off far more often than not, because the highest-damage legal attack is the one most players choose most of the time.

function attackSignature(r: AttackResolution): string {
  return JSON.stringify([
    r.attackerCardId, r.defenderCardId, r.attackName, r.appliedDamage,
    r.knockout, r.inflicted, r.selfDamage, r.fizzled, r.benchDamage,
    r.defenderRemainingHpAfter,
  ]);
}
useAnimation.ts: a clip queued ahead of time is only the clip for a resolution that matches it exactly.

Bet three: the CPU will do it again

Computer opponents repeat themselves. A CPU that has found its best attack will use it every turn until something changes, and a clip made for that exact request (same prompt, same two keyframes, same duration and resolution) is by construction the same shot. So clips generated for the CPU are filed under a hash of the request and served from that file up to three times before being regenerated. A served repeat submits nothing and charges nothing; the first poll simply finds it complete.

The player's own attacks are never reused. Watching your own Thunderbolt play back identically twice would feel like a loop, and it is the player's attention, not the CPU's, that the game is spending its budget on.

Designing for the bet to lose

Every one of these bets can lose, and the design assumes it will. The fal.ai queue is asynchronous: submitting returns a request id and the client polls, slowly at first and faster after the point where clips typically start landing. The job is written to the document store as well as held in memory, so a clip queued before a redeploy can still be collected afterwards; fal holds the work, and the store holds what the work was for. If generation fails outright, the two keyframes play with a caption, the attack resolves anyway, and the board is correct. A per-player monthly cap on generated seconds, set by the player, is charged at queue time and refuses further clips the same way.

The reason all of that is safe is the subject of the companion article: the engine decides every outcome before generation starts, so a missing or late clip never changes the game. Latency engineering around a generative model is only tractable when the model is decoration. Once nothing depends on it, you can start it early, cache it aggressively, guess at it, reuse it, and drop it, and the worst case is a plainer picture.

The overall architecture, including how the same engine runs on the server for online play, is in the Pokémon TCG Live Attacks case study. The warmDirections and attackSignature functions above are the two places I would start reading.

Book a 30-min callEmail about this work