Skip to content
Blog

← All articles

Running a jti Replay Store in Production: Redis Failover, Eviction, and ECS

A Redis replay store that works on one machine can accept replayed tokens in production. We measured how: ElastiCache’s default eviction policy let 96,689 of 100,000 replays through, and a 7-second network partition lost 9,027 jtis the API had already accepted. The fixes, measured too: noeviction, min-replicas-to-write, WAIT, fail-fast clients, hash tags in cluster mode, and revocation that reaches every ECS task. Tested on Redis 8.2 and Valkey 8.1, with validated Terraform.

By 21 min read

The jti article built a replay store in one Redis command: SET with NX and an expiry. Fifty servers raced the same token, and exactly one won. That’s correct, on one Redis that never runs out of memory, never fails over, and always answers.

Production Redis does all three. This article runs the same replay store against the failures it will meet on a real deployment (an API on Amazon ECS, the store on ElastiCache) and counts the replays that get through. The default eviction policy accepted 97% of 100,000 replayed tokens. A 7-second network partition lost 9,027 jtis that the API had already accepted, so every one of those tokens could be used again. Then it measures each fix and what each one costs. Every example ran against Redis 8.2 and Valkey 8.1 (the engine ElastiCache runs) before publishing; the AWS configuration was checked with terraform validate but not deployed.

The short answer#

The architecture#

The setup is the common one. An API runs as an ECS service, several Fargate tasks spread over three Availability Zones. Each request carrying a single-use token (a client assertion, a DPoP proof, a logout token) is verified, and then its jti is recorded with one SET NX on the ElastiCache primary. Access tokens aren’t single-use; for them, Redis holds the revocation denylist that each request checks.

Load balancerHTTPSAZ aAPI tasks (ECS)verify, then SET NXAZ bAPI tasks (ECS)verify, then SET NXAZ cAPI tasks (ECS)verify, then SET NXPrimaryevery SET NX lands hereReplicaa copy, slightly behindReplicaa copy, slightly behinddashed: asynchronous replication · ElastiCache (Valkey), Multi-AZ, automatic failover
Every replay check goes to the primary. The replicas receive each write a moment later: that gap is where a failover loses jtis.

There’s one primary because a replay check has to be a single atomic decision. Reading from replicas would be wrong here: a replica that hasn’t yet received a jti will say it’s new. The replicas are there to take over, and everything below is about what happens during that takeover, and when the primary can’t take more data or can’t answer at all.

The store is small. The jti article measured 116 bytes per entry in Redis 8.2, and each entry lives only until its token expires. A thousand single-use tokens a second, each valid for five minutes plus 30 seconds of leeway, keeps about 330,000 entries: under 40 MB. A cache.r7g.large node has 13 GB. Memory isn’t the problem; the defaults are.

Eviction: the default that accepts replays#

When Redis reaches maxmemory, the eviction policy decides what happens to the next write. A cache deletes something old to make room, which is exactly right for a cache. For a replay store, deleting an entry means forgetting that a token was used, so the next copy of that token is accepted.

ElastiCache’s parameter groups default to volatile-lru: evict the least recently used key that has an expiry. A replay store sets an expiry on every key, so every entry is a candidate. ElastiCache Serverless behaves the same way when it reaches its storage limit, and doesn’t let you change it. To see the effect, this fills a 4 MB Redis with 100,000 tokens, then replays all of them:

eviction.mjs
// eviction.mjs: fill a small Redis with jtis, then replay every token it accepted. How many get in twice?
// Uses CONFIG SET to switch policies; on ElastiCache you set maxmemory-policy in the parameter group instead.
import Redis from "ioredis";
import { firstUse } from "./replay-redis.mjs";

const redis = new Redis(process.env.REDIS_URL);
const TOKENS = 100_000;
const keepUntil = Math.floor(Date.now() / 1000) + 3600; // every token is still valid for an hour

// Try each jti once; an error from Redis means the request is refused, not accepted.
async function offer(jtis) {
  let accepted = 0, refused = 0;
  for (let i = 0; i < jtis.length; i += 500) {
    const batch = await Promise.all(
      jtis.slice(i, i + 500).map((jti) => firstUse(redis, "https://client.example", jti, keepUntil).catch(() => null)),
    );
    accepted += batch.filter((r) => r === true).length;
    refused += batch.filter((r) => r === null).length;
  }
  return { accepted, refused };
}

await redis.config("SET", "maxmemory", "4mb");
for (const policy of ["volatile-lru", "allkeys-lru", "noeviction"]) {
  await redis.flushall();
  await redis.config("SET", "maxmemory-policy", policy);
  const jtis = Array.from({ length: TOKENS }, () => crypto.randomUUID());
  const first = await offer(jtis);
  const replay = await offer(jtis); // an attacker replays all 100,000
  console.log(
    `${policy.padEnd(12)} first pass: ${first.accepted.toLocaleString("en-US")} accepted, ` +
      `${first.refused.toLocaleString("en-US")} refused · replays accepted: ${replay.accepted.toLocaleString("en-US")}`,
  );
}
await redis.flushall();
await redis.config("SET", "maxmemory", "0"); // back to no limit, the Redis default
await redis.config("SET", "maxmemory-policy", "noeviction");
redis.disconnect();
volatile-lru first pass: 100,000 accepted, 0 refused · replays accepted: 96,689
allkeys-lru  first pass: 100,000 accepted, 0 refused · replays accepted: 97,649
noeviction   first pass: 26,788 accepted, 73,212 refused · replays accepted: 0

With either LRU policy, every token was accepted the first time, and then 97% were accepted again. Nothing failed, and nothing was logged; the store forgot. Valkey 8.1 gave the same picture (93% of replays accepted). The test checks for more than 85% on both engines, because LRU in Redis is approximate: it samples a few keys rather than tracking every access, so the exact count varies from run to run.

With noeviction, Redis refuses the write instead (OOM command not allowed), the replay check throws, and the request is refused. Not one replay got through. The cost is clear in the first pass: once the store was full, 73% of new, legitimate tokens were refused too. That’s the right failure for a security control, but it’s still an outage, so size the store with room to spare and alarm long before it fills:

  • Alarm on memory, at 75% (DatabaseMemoryUsagePercentage). At 100% with noeviction, logins fail.
  • Alarm on any eviction (Evictions > 0). With noeviction, there should never be one; if there is, the policy isn’t what you think.
  • Leave ElastiCache’s reserved-memory-percent at its default of 25. Replication buffers and failover need that memory. In the test, attaching one replica cut the number of jtis the 4 MB store could hold from about 27,000 to 16,000, because the replication backlog counts too.
  • Give the replay store its own cluster if anything else uses Redis as a cache. The policy is per node, and a cache wants the opposite of a replay store.

Failover: jtis Redis forgets#

Redis replicates asynchronously. The primary answers OK to the SET NX, the API accepts the token, and the write reaches the replicas a moment later. If the primary fails in that moment and a replica takes over, the new primary has never heard of that jti. The token can be used again.

How long is the moment? To measure it, the test runs a primary, one replica, and three Redis Sentinels (the processes that detect a failed primary and promote a replica), with a client accepting 500 tokens a second through the primary. Then it breaks the primary in two ways, and afterward asks the Sentinels which node is primary and checks every jti the client was told had been accepted:

  • A crash: the primary is killed.
  • A partition: the primary is cut off from the replica and the Sentinels for 7 seconds, but the client can still reach it. This is the case that hurts: an API task with an open connection to a primary the rest of the system has given up on.
What brokeSettingsjtis acceptedLost (replayable)
Crashdefaults1,0650
7 s partitiondefaults9,9529,027
7 s partitionmin-replicas-to-write 1, lag 2 s2,3171,301
7 s partitionWAIT 1 on every write1,0040

The crash lost nothing: replication on a local network runs well under a millisecond behind, and the client couldn’t write to a dead primary. (It stayed pointed at the old primary, so it refused everything after the crash. A real client reconnects to the new one within seconds, through Sentinel or ElastiCache’s primary endpoint.)

The partition is where it goes wrong, and the per-second timeline shows why it lost more than 7 seconds’ worth. The cut came 1.7 seconds into the run. One second later, the Sentinels promoted the replica. The cut healed at 9 seconds. But the old primary didn’t know it had been replaced: it kept accepting writes from the client until the Sentinels reconfigured it, about 10 seconds after it reappeared. Then it became a replica of the new primary, dropped its data to resynchronize, and every jti it had accepted since the cut was gone: 18 seconds of tokens. After that, the client’s writes failed with READONLY.

Closing the window: min-replicas and WAIT#

min-replicas-to-write 1 with min-replicas-max-lag 2 tells the primary to refuse writes when no replica has acknowledged it for more than 2 seconds. The partitioned primary started refusing (NOREPLICAS) about 2.5 seconds after the cut, and the loss fell from 9,027 to 1,301: the window is now bounded by the lag setting, not by how long the partition lasts. ElastiCache exposes both as parameters (the default for min-replicas-to-write is 0, off). Set it with two replicas, not one: with a single replica, losing that replica stops all writes.

WAIT 1 goes further for the requests that matter. After the SET NX, it blocks until at least one replica has the write, or a timeout passes. If no replica confirms, the token isn’t accepted:

durable.mjs
// durable.mjs: accept a jti only once at least one replica has it too.
import { createHash } from "node:crypto";

// Like firstUse, but SET NX and WAIT go out together in one round trip. WAIT returns how many replicas
// have every write this connection made so far. Fewer than asked for, within timeoutMs, means a failover
// could lose this jti, so the request is refused (the client retries with a new token).
export async function firstUseDurable(redis, iss, jti, keepUntil, { replicas = 1, timeoutMs = 50 } = {}) {
  const id = createHash("sha256").update(JSON.stringify([iss, jti])).digest("base64url");
  const [[setErr, set], [waitErr, acked]] = await redis
    .pipeline()
    .set(`jti:${id}`, "1", "EXAT", keepUntil, "NX")
    .wait(replicas, timeoutMs)
    .exec();
  if (setErr) throw setErr;
  if (set !== "OK") return false; // seen before: a replay
  if (waitErr || acked < replicas) throw new Error("not replicated: refusing the request");
  return true;
}

That lost nothing. It also accepted nothing during the partition: every request waited out the 50 ms timeout and was refused, so the client’s throughput dropped from 500 a second to 10. For a single-use token that’s the right trade, because the client can retry with a new token once the store has failed over. There’s one subtlety: when WAIT times out, the jti is still recorded on the primary, so a retry of the same token would be refused as a replay. Clients make a new assertion per request anyway.

On a healthy pair, waiting for the replica costs very little:

latency.mjs
// latency.mjs: what does waiting for a replica cost? 5,000 replay checks each way, one at a time.
import Redis from "ioredis";
import { firstUse } from "./replay-redis.mjs";
import { firstUseDurable } from "./durable.mjs";

const redis = new Redis(process.env.REDIS_URL);
const keepUntil = Math.floor(Date.now() / 1000) + 90;
const ms = (x) => x.toFixed(2);

for (const [name, use] of [["SET NX", firstUse], ["SET NX + WAIT 1", firstUseDurable]]) {
  const times = [];
  for (let i = 0; i < 5000; i++) {
    const start = performance.now();
    await use(redis, "https://client.example", crypto.randomUUID(), keepUntil);
    times.push(performance.now() - start);
  }
  times.sort((a, b) => a - b);
  const at = (p) => times[Math.floor((p / 100) * times.length)];
  console.log(`${name.padEnd(15)} p50 ${ms(at(50))} ms · p99 ${ms(at(99))} ms · max ${ms(times.at(-1))} ms`);
}
redis.disconnect();
SET NX          p50 0.07 ms · p99 0.22 ms · max 12.50 ms
SET NX + WAIT 1 p50 0.12 ms · p99 0.30 ms · max 3.23 ms

That’s on one Docker host. Across Availability Zones, each WAIT adds about one network round trip between zones; measure it in your own region. Two limits: WAIT isn’t available on ElastiCache Serverless, which lists it among its restricted commands, so this needs a node-based cluster. And WAIT makes a write survive the loss of the primary, not of everything: it’s not the same as a database commit. For the rare system where a replay is worse than any outage, keep single-use tokens in a database with synchronous replication instead (the jti article has the PostgreSQL version).

When Redis doesn’t answer#

A failover takes seconds; during them, Redis is either silent or gone. What the API does then depends almost entirely on two client settings, and the defaults are built for caches. This measures a replay check against a Redis that is paused for 2 seconds, and against one that isn’t there at all:

failfast.mjs
// failfast.mjs: how long does a replay check take to fail when Redis is stalled, or gone?
import Redis from "ioredis";
import { firstUse } from "./replay-redis.mjs";

// The settings for a replay store: give up quickly, and never queue commands while disconnected.
export const FAIL_FAST = {
  commandTimeout: 100, // ms: a replay check normally takes well under 1 ms
  maxRetriesPerRequest: 1,
  enableOfflineQueue: false, // while disconnected, fail at once instead of queueing
  retryStrategy: (times) => Math.min(times * 100, 1000) + Math.floor(Math.random() * 100), // reconnect with jitter
};

if (import.meta.main) {
  const keepUntil = () => Math.floor(Date.now() / 1000) + 90;
  async function timed(redis) {
    const start = performance.now();
    const result = await firstUse(redis, "https://client.example", crypto.randomUUID(), keepUntil()).then(
      (ok) => (ok ? "accepted" : "replayed"),
      (e) => `error: ${e.message}`,
    );
    return `${result} after ${Math.round(performance.now() - start).toLocaleString("en-US")} ms`;
  }

  // 1. Redis is up but not answering for 2 seconds (as during a failover or a long command).
  const admin = new Redis(process.env.REDIS_URL);
  for (const [name, options] of [["default client", {}], ["fail-fast client", FAIL_FAST]]) {
    const redis = new Redis(process.env.REDIS_URL, options);
    if (redis.status !== "ready") await new Promise((r) => redis.once("ready", r));
    await admin.client("PAUSE", 2000, "ALL");
    console.log(`stalled, ${name}:`, await timed(redis));
    await admin.client("UNPAUSE");
    redis.disconnect();
  }

  // 2. Nothing listening at all (a node that's gone).
  const gone = process.env.REDIS_URL.replace(/:\d+$/, ":6390");
  for (const [name, options] of [["default client", {}], ["fail-fast client", FAIL_FAST]]) {
    const redis = new Redis(gone, { ...options, lazyConnect: true });
    redis.connect().catch(() => {}); // the first attempt fails; we're measuring the request, not the connect
    redis.on("error", () => {});
    await new Promise((r) => setTimeout(r, 50));
    console.log(`down, ${name}:`, await timed(redis));
    redis.disconnect();
  }
  admin.disconnect();
}
stalled, default client: accepted after 2,007 ms
stalled, fail-fast client: error: Command timed out after 101 ms
down, default client: error: Reached the max retries per request limit (which is 20). … after 73,884 ms
down, fail-fast client: error: Stream isn't writeable and enableOfflineQueue options is false after 0 ms

The default client has no command timeout, queues commands while disconnected, and retries each one 20 times with growing delays. Against a missing node, one request waited 74 seconds. On an ECS task, that’s 74 seconds of a held connection, a held thread of work, and a load balancer that eventually times out anyway, multiplied by every request in flight. The fail-fast settings turn the same outage into an immediate, clear error. The jitter in retryStrategy matters too: after a failover, every task reconnects at once, and a little randomness spreads them out.

Once the check can fail quickly, decide what a failure means. It isn’t the same for every token:

policy.mjs
// policy.mjs: what an API task does when the replay store can't answer in time.
import Redis from "ioredis";
import { firstUse } from "./replay-redis.mjs";
import { FAIL_FAST } from "./failfast.mjs";

// Single-use tokens (client assertions, DPoP proofs): fail closed. An unchecked one could be a replay,
// and the client can simply retry with a new token.
export async function checkSingleUse(redis, iss, jti, keepUntil) {
  try {
    return (await firstUse(redis, iss, jti, keepUntil)) ? { status: 200 } : { status: 401, error: "replayed jti" };
  } catch {
    return { status: 503, error: "replay store unavailable" };
  }
}

// Revocation of short-lived access tokens: a choice. Failing open keeps the API up during a Redis outage,
// at the price of honoring a revoked token for that long. Count it, and alarm on it.
export async function checkRevoked(redis, key, { failOpen = true, onSkip = () => {} } = {}) {
  try {
    return (await redis.exists(key)) === 1 ? { status: 401, error: "revoked" } : { status: 200 };
  } catch {
    onSkip();
    return failOpen ? { status: 200, warning: "revocation not checked" } : { status: 503, error: "revocation store unavailable" };
  }
}

if (import.meta.main) {
  const admin = new Redis(process.env.REDIS_URL);
  const redis = new Redis(process.env.REDIS_URL, FAIL_FAST);
  await new Promise((r) => redis.once("ready", r));
  await admin.client("PAUSE", 1000, "ALL"); // Redis stalls for a second
  const keepUntil = Math.floor(Date.now() / 1000) + 90;
  console.log("client assertion:", await checkSingleUse(redis, "https://client.example", crypto.randomUUID(), keepUntil));
  console.log("access token:    ", await checkRevoked(redis, `revoked:${crypto.randomUUID()}`));
  console.log("access token, fail closed:", await checkRevoked(redis, `revoked:${crypto.randomUUID()}`, { failOpen: false }));
  await admin.client("UNPAUSE");
  redis.disconnect();
  admin.disconnect();
}
client assertion: { status: 503, error: 'replay store unavailable' }
access token:     { status: 200, warning: 'revocation not checked' }
access token, fail closed: { status: 503, error: 'revocation store unavailable' }
  • Single-use tokens fail closed. An assertion you couldn’t record might be a replay, and the client can retry with a new one in a few seconds. Return 503 with Retry-After.
  • Revocation checks are a choice. Failing open keeps the API up during a Redis outage, and the worst case is a revoked access token honored for the length of the outage, which is bounded by the token’s lifetime anyway. If revocation is your response to a stolen token, fail closed. Either way, count the skips and alarm on them.

Cluster mode and hash tags#

ElastiCache in cluster mode splits keys across shards by hash slot (16,384 of them). The replay check is one command on one key, so it works unchanged: each jti hashes to some slot, and the client sends it to the right shard. Trouble starts with a script that touches two keys, for example accepting a client’s assertion once and counting it against that client’s per-minute quota in one atomic step:

cluster.mjs
// cluster.mjs: accept a client's assertion once AND count it against that client's quota, in one atomic script.
// In Redis Cluster, a script may only touch keys in one hash slot.
import { createHash } from "node:crypto";
import Redis from "ioredis";

const [host, port] = process.env.CLUSTER.split(":");
const redis = new Redis.Cluster([{ host, port: Number(port) }]);

// 1 if the jti is new and the client is under its limit; 0 if replayed; -1 if over the limit.
const ACCEPT = `
if redis.call('EXISTS', KEYS[1]) == 1 then return 0 end
local n = redis.call('INCR', KEYS[2])
if n == 1 then redis.call('EXPIRE', KEYS[2], 60) end
if n > tonumber(ARGV[2]) then return -1 end
redis.call('SET', KEYS[1], '1', 'EXAT', ARGV[1])
return 1`;
const hash = (s) => createHash("sha256").update(s).digest("base64url");
const keepUntil = Math.floor(Date.now() / 1000) + 90;
const client = "client-42";

// Without a hash tag, the two keys land in different slots.
const plain = [`jti:${hash(client + crypto.randomUUID())}`, `quota:${client}`];
await redis.eval(ACCEPT, 2, ...plain, keepUntil, 100).catch((e) => console.log("no tag:", e.message.split(" ")[0]));

// With {client-42} in both names, only that part is hashed: same slot, and the script runs.
const tagged = [`jti:{${client}}:${hash(crypto.randomUUID())}`, `quota:{${client}}`];
console.log("tagged:", await redis.eval(ACCEPT, 2, ...tagged, keepUntil, 100), "then", await redis.eval(ACCEPT, 2, ...tagged, keepUntil, 100));

// The price: every jti from that client now lives in one slot, so on one shard.
const slots = async (key) => new Set(await Promise.all(Array.from({ length: 10_000 }, () => redis.cluster("KEYSLOT", key()))));
console.log("10,000 jtis, untagged:", (await slots(() => `jti:${hash(crypto.randomUUID())}`)).size, "slots");
console.log("10,000 jtis, tagged:  ", (await slots(() => `jti:{${client}}:${hash(crypto.randomUUID())}`)).size, "slot");
redis.disconnect();
no tag: CROSSSLOT
tagged: 1 then 0
10,000 jtis, untagged: 7483 slots
10,000 jtis, tagged:   1 slot

Without a hash tag, the two keys land in different slots, and the cluster refuses the script with CROSSSLOT, even when both slots happen to live on the same node. With {client-42} in both key names, only that part is hashed, so they share a slot, and the script runs: the token is accepted once, then refused as a replay.

The price is in the last two lines. Untagged, 10,000 jtis spread over 7,483 slots; tagged, every jti from that client lands in one slot, and so on one shard. A big client becomes a hot shard, and its keys can’t be spread by adding shards. Use a tag only where you need atomicity across keys, tag by something small (the client, not a whole tenant), and keep the plain replay check untagged. The Redis Lua rate limiter goes deeper into scripts like this one.

Revocation across every task#

The jti article’s denylist answers “is this token revoked?” with one EXISTS, well under a millisecond. Most APIs should stop there. At very high request rates, some teams add a short in-process cache of the answers, and then a revocation must reach every task’s cache. Redis pub/sub does that quickly, but it delivers each message at most once: a task that’s reconnecting when the message is sent never sees it. This runs 20 tasks, each caching “not revoked” for one second, and revokes a token while one of them is reconnecting:

revocation-push.mjs
// revocation-push.mjs: 20 API tasks cache "not revoked" answers for one second, and hear about revocations
// over Redis pub/sub. How fast does a revocation reach all of them, and what if one misses the message?
import Redis from "ioredis";

const CACHE_MS = 1000;
const redis = new Redis(process.env.REDIS_URL); // shared here for brevity; each task would have its own

function makeTask() {
  const cache = new Map(); // key -> { revoked, until }
  const sub = new Redis(process.env.REDIS_URL);
  const ready = sub.subscribe("revoked");
  sub.on("message", (_, key) => { cache.set(key, { revoked: true, until: Infinity }); task.heard = performance.now(); });
  const task = {
    sub,
    ready,
    heard: 0,
    async isRevoked(key) {
      const hit = cache.get(key);
      if (hit && hit.until > Date.now()) return hit.revoked;
      const revoked = (await redis.exists(key)) === 1; // the denylist in Redis stays the source of truth
      cache.set(key, { revoked, until: Date.now() + CACHE_MS });
      return revoked;
    },
  };
  return task;
}

const tasks = Array.from({ length: 20 }, makeTask);
await Promise.all(tasks.map((t) => t.ready));
const key = `revoked:${crypto.randomUUID()}`;
await Promise.all(tasks.map((t) => t.isRevoked(key))); // every task has cached "not revoked"

// Task 20 is reconnecting at the moment of the revocation.
tasks[19].sub.disconnect();
const sent = performance.now();
await redis.set(key, "1", "EX", 930);
await redis.publish("revoked", key);
await new Promise((r) => setTimeout(r, 50));
const delays = tasks.slice(0, 19).map((t) => t.heard - sent);
console.log(`19 tasks heard in ${Math.max(...delays).toFixed(1)} ms or less`);

// Task 20 never got the message: it keeps accepting the token until its cached answer expires.
let stale = 0;
while (!(await tasks[19].isRevoked(key))) { stale = performance.now() - sent; await new Promise((r) => setTimeout(r, 5)); }
console.log(`task 20 missed it, and accepted the revoked token for ${Math.round(stale / 100) * 100} ms more`);
tasks.forEach((t) => t.sub.disconnect());
redis.disconnect();
19 tasks heard in 1.2 ms or less
task 20 missed it, and accepted the revoked token for 1000 ms more

The 19 connected tasks dropped the token within about a millisecond. The 20th went on accepting it until its cached answer expired. That’s the design: Redis stays the source of truth, pub/sub makes revocation fast in the normal case, and the cache lifetime is the worst-case delay. Pick that lifetime as the longest you can accept a revoked token, not as a performance knob. On ElastiCache Serverless, use SUBSCRIBE, not PSUBSCRIBE; pattern subscriptions are restricted there.

The ECS side#

  • One connection per task, plus one for pub/sub. Redis handles commands one at a time per connection but pipelines them, so a pool rarely helps. Six tasks hold 12 connections; a rolling deploy with maximumPercent 200 briefly doubles that. ElastiCache allows 65,000 clients per node, so the count isn’t the risk; the reconnect storm after a failover is, which is why the retry strategy has jitter.
  • TLS and AUTH. Turn on in-transit encryption, give the store a security group that only the API tasks’ group can reach on port 6379, and put the AUTH token in Secrets Manager, injected through the task definition’s secrets, never its environment.
  • Health checks shouldn’t ping Redis. If the container health check fails when Redis is unreachable, ECS replaces every task during a failover, and the API restarts at the moment it most needs to stay up. Report Redis trouble through metrics and the 503s above, not through task health.
  • Shut down cleanly. ECS sends SIGTERM and, on Fargate, waits 30 seconds by default before killing the task. Stop accepting requests, let in-flight replay checks finish, then call quit().
  • Keep the clocks honest. Each entry expires at the token’s exp plus your leeway, compared with Redis’s clock. Your servers keep accurate time on AWS; the leeway is there for the clients’ clocks, which may not.

The infrastructure as code#

Everything above, as Terraform: the parameter group with the three settings that matter, a Multi-AZ replication group with a primary and two replicas, the two alarms, and the ECS service. It’s checked with terraform validate and terraform fmt against the AWS provider (6.73), but it hasn’t been applied, so treat sizes and names as a starting point:

infra/main.tf
# infra/main.tf: the replay store on ElastiCache (Valkey), and the ECS service that uses it.
# Checked with `terraform validate`; not applied. Names, sizes and the network come from your own setup.

terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "vpc_id" { type = string }
variable "private_subnet_ids" { type = list(string) }
variable "ecs_cluster_arn" { type = string }
variable "api_image" { type = string }
variable "execution_role_arn" { type = string }
variable "task_role_arn" { type = string }
variable "auth_token_secret_arn" { type = string } # Secrets Manager secret holding the Valkey AUTH token
variable "auth_token" {
  type      = string
  sensitive = true
}
variable "alarm_topic_arn" { type = string }

# --- Network: only the API tasks can reach the store. ---
resource "aws_security_group" "api" {
  name   = "api-tasks"
  vpc_id = var.vpc_id
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "replay_store" {
  name   = "jti-replay-store"
  vpc_id = var.vpc_id
  ingress {
    from_port       = 6379
    to_port         = 6379
    protocol        = "tcp"
    security_groups = [aws_security_group.api.id]
  }
}

resource "aws_elasticache_subnet_group" "replay_store" {
  name       = "jti-replay-store"
  subnet_ids = var.private_subnet_ids
}

# --- The settings that matter for a replay store. ---
resource "aws_elasticache_parameter_group" "replay_store" {
  name   = "jti-replay-store"
  family = "valkey8"

  # The default is volatile-lru, which evicts keys with a TTL: every jti. Refuse writes instead.
  parameter {
    name  = "maxmemory-policy"
    value = "noeviction"
  }
  # The primary stops accepting writes when no replica has acknowledged it for 2 seconds.
  parameter {
    name  = "min-replicas-to-write"
    value = "1"
  }
  parameter {
    name  = "min-replicas-max-lag"
    value = "2"
  }
}

resource "aws_elasticache_replication_group" "replay_store" {
  replication_group_id = "jti-replay-store"
  description          = "Single-use JWT IDs (jti) and the revocation denylist"
  engine               = "valkey"
  engine_version       = "8.1"
  node_type            = "cache.r7g.large"
  num_cache_clusters   = 3 # a primary and two replicas, in different Availability Zones
  parameter_group_name = aws_elasticache_parameter_group.replay_store.name
  subnet_group_name    = aws_elasticache_subnet_group.replay_store.name
  security_group_ids   = [aws_security_group.replay_store.id]

  automatic_failover_enabled = true
  multi_az_enabled           = true
  at_rest_encryption_enabled = true
  transit_encryption_enabled = true
  auth_token                 = var.auth_token
  snapshot_retention_limit   = 0 # nothing here is worth restoring: every entry expires within minutes
}

# --- Alarms: an eviction is a replay hole; full memory means refused logins. ---
# ElastiCache names the nodes <group>-001, -002, -003. (member_clusters isn't known until after apply.)
locals {
  store_nodes = toset([for i in range(1, 4) : format("jti-replay-store-%03d", i)])
}
resource "aws_cloudwatch_metric_alarm" "evictions" {
  for_each            = local.store_nodes
  alarm_name          = "jti-store-evictions-${each.value}"
  namespace           = "AWS/ElastiCache"
  metric_name         = "Evictions"
  dimensions          = { CacheClusterId = each.value }
  statistic           = "Sum"
  period              = 60
  evaluation_periods  = 1
  comparison_operator = "GreaterThanThreshold"
  threshold           = 0
  alarm_actions       = [var.alarm_topic_arn]
}

resource "aws_cloudwatch_metric_alarm" "memory" {
  for_each            = local.store_nodes
  alarm_name          = "jti-store-memory-${each.value}"
  namespace           = "AWS/ElastiCache"
  metric_name         = "DatabaseMemoryUsagePercentage"
  dimensions          = { CacheClusterId = each.value }
  statistic           = "Maximum"
  period              = 60
  evaluation_periods  = 3
  comparison_operator = "GreaterThanThreshold"
  threshold           = 75
  alarm_actions       = [var.alarm_topic_arn]
}

# --- The API on ECS (Fargate). ---
resource "aws_ecs_task_definition" "api" {
  family                   = "api"
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "512"
  memory                   = "1024"
  execution_role_arn       = var.execution_role_arn
  task_role_arn            = var.task_role_arn
  container_definitions = jsonencode([{
    name         = "api"
    image        = var.api_image
    essential    = true
    portMappings = [{ containerPort = 8080 }]
    environment = [
      { name = "REPLAY_STORE_HOST", value = aws_elasticache_replication_group.replay_store.primary_endpoint_address },
      { name = "REPLAY_STORE_TLS", value = "true" },
    ]
    secrets = [{ name = "REPLAY_STORE_AUTH", valueFrom = var.auth_token_secret_arn }]
  }])
}

resource "aws_ecs_service" "api" {
  name            = "api"
  cluster         = var.ecs_cluster_arn
  task_definition = aws_ecs_task_definition.api.arn
  desired_count   = 6
  launch_type     = "FARGATE"

  # A rolling deploy runs old and new tasks side by side: up to twice the connections for a few minutes.
  deployment_minimum_healthy_percent = 100
  deployment_maximum_percent         = 200
  deployment_circuit_breaker {
    enable   = true
    rollback = true
  }

  network_configuration {
    subnets         = var.private_subnet_ids
    security_groups = [aws_security_group.api.id]
  }
}

Two details that aren’t obvious from the file. The alarms list the node names explicitly, because ElastiCache names them <group>-001, -002, and -003, and the replication group’s member_clusters isn’t known until after the first apply, which for_each can’t use. And snapshot_retention_limit = 0 is deliberate: every entry expires within minutes, so a snapshot restored an hour later would contain nothing still useful.

More than one region#

ElastiCache Global Datastore replicates a primary region to others asynchronously, which is the failover problem again, across an ocean. A replay store shouldn’t depend on it. Instead, make a single-use token valid in only one region: put the region’s own URL in the token’s aud (as client assertions already do, with the token endpoint), and keep a separate store per region. A token replayed to another region then fails its audience check before any store is consulted. Revocation is different, because an access token works everywhere: write revocations to every region’s denylist, or accept that a revocation reaches distant regions only as fast as Global Datastore replicates.

Production checklist#

SettingDefaultFor a replay storeWhy
maxmemory-policyvolatile-lru (ElastiCache)noevictionLRU accepted 97% of replays
min-replicas-to-write01 (with two replicas)Bounds a partition’s loss to the lag
min-replicas-max-lag10 s2 sThe size of that bound
WAIT for single-use tokensnot usedWAIT 1, 50 ms0 lost in a partition; not on Serverless
Client command timeoutnone (ioredis)100 ms74 s to fail without it
Offline queueonoffFail at once while disconnected
Redis unreachable, single-use token(your code)503, fail closedAn unchecked token may be a replay
Alarmsnonememory > 75%, evictions > 0Full means refused logins
SnapshotsvariesoffNothing in the store outlives a token

FAQ#

Why not just use DynamoDB?

You can. A conditional PutItem (attribute_not_exists) is the same atomic first-use check, and it’s written to multiple Availability Zones before it’s acknowledged, so a failover doesn’t lose it. DynamoDB’s TTL deletes expired items lazily (AWS says within a few days), so also compare the stored expiry when you read. The trade is latency: single-digit milliseconds instead of well under one.

Is ElastiCache Serverless a good fit?

For revocation, yes. For single-use tokens, with care: it evicts entries with a TTL when it reaches its storage limit, you can’t change that policy, and WAIT isn’t available. Set a storage limit well above your needs, alarm at 75% of it, and accept a failover’s small window, or use a node-based cluster.

Should the replay store and the rate limiter share a cluster?

They can, as long as both want noeviction. Don’t share with a cache. A cache wants old data evicted, a replay store must never lose it, and the eviction policy applies to the whole node.

Does Redis persistence (AOF) help?

Not with failover. Persistence protects against restarting the same node; a failover promotes a different node that never received the write. ElastiCache doesn’t offer AOF on current engines anyway. Replicas and WAIT are the tools here.

Do access tokens need a replay check?

No. They’re used on every request by design. Their jti is for revocation and logs; the jti article covers which tokens are single-use, and the JWT architecture guide covers the rest of token verification.

Try it in your browser

  • JWT Decoder, Encoder & Editor: decode a client assertion to check its jti, exp, and aud before you decide how long to remember it.
  • UUID Generator: generate the random v4 UUIDs a client should use as jti values.
  • Hash Generator: compute the SHA-256 hash the examples use to turn an issuer and jti into a fixed-size Redis key.