All snippets
TypeScript

Run a job once per time window with a Redis lock

Let any number of callers trigger a job, but run it at most once every 5 minutes.

RedisUpstashCron

The uptime monitor on this site can be started by a scheduled function, a manual call or a retry. Instead of coordinating them, each one tries to claim the current 5-minute window in Redis. SET ... NX succeeds for exactly one caller, and the rest return straight away.

ts
import { Redis } from "@upstash/redis";

const redis = Redis.fromEnv();
const WINDOW_SECONDS = 5 * 60;

/** Runs `job` at most once per window, however often this is called. */
export async function runOncePerWindow(name: string, job: () => Promise<void>) {
  const window = Math.floor(Date.now() / 1000 / WINDOW_SECONDS);

  // NX: only set if missing. The expiry cleans the lock up on its own.
  const claimed = await redis.set(`lock:${name}:${window}`, 1, {
    nx: true,
    ex: WINDOW_SECONDS * 2,
  });

  if (claimed === null) return false; // someone else has this window

  await job();

  return true;
}

Keying the lock by window number, not by time, means there's nothing to release: the next window has a different key. Keep the expiry longer than the window so a slow job can't overlap the next one.

From the projectPortfolio