In 04-01, AgendaViva asked an external service for the forecast. The opposite direction exists too: another system calls us to tell us something has happened. That's a webhook, a POST nobody asked for, and it raises questions an ordinary request didn't. Is it who it claims to be? Have I already received it? Is it late? What do I answer so it doesn't keep repeating it forever?

In this lesson the city's venues will notify us of capacity changes, and you'll see how to verify, apply and acknowledge those notifications. Then we'll switch sides: AgendaViva will send emails through a third-party API, https://api.mail.example, which is sometimes slow, sometimes fails and sometimes asks you to wait. Both halves share one idea: on a network, any message can be lost, duplicated or arrive out of order.

  1. Anatomy of a webhook

The venues' system will send this when a venue's capacity changes:

{
  "id": "ntf_7f3c",
  "type": "capacity.updated",
  "occurredAt": "2028-04-02T09:15:00Z",
  "data": { "venue": "the-factory", "capacity": 60 }
}
POST /api/webhooks/venues
Content-Type: application/json
X-Venues-Signature: t=1838279700,v1=5f2b…64 hex digits…

The questions and their answers:

Problem Defense
Anyone can call the URL A signature with a shared secret
Someone captures a genuine notification and resends it A timestamp inside what's signed
The sender doesn't get our response and tries again Store the identifier and don't apply it twice
They arrive out of order Compare occurredAt
We take too long and the sender considers the delivery failed Do the bare minimum and answer
A type we don't know shows up Acknowledge it and ignore it

The status code we answer with is the protocol. The sender doesn't read our body: with a 2xx it considers it delivered; with a 5xx, or no response, it will retry for hours; with a 4xx, each one does its own thing. A 200 out of habit, returned after a database failure, loses the notification forever.

  1. The signature

Sender and receiver share a secret that never travels. The sender computes a cryptographic digest of the body with that secret (HMAC) and sends it; we repeat the computation and compare. Without the secret, nobody can produce the signature, and changing a single byte of the body invalidates it.

// lib/security/signatures.ts
import 'server-only'
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'

const TOLERANCE = 5 * 60 // Seconds
const FORMAT = /^t=(\d{1,12}),v1=([0-9a-f]{64})$/

function computeSignature(secret: string, timestamp: string, body: Uint8Array): Buffer {
  return createHmac('sha256', secret).update(`${timestamp}.`).update(body).digest()
}

export function verifySignature(
  header: string | null,
  body: Uint8Array,
  secrets: string[],
  now: Date,
): boolean {
  const parts = FORMAT.exec(header ?? '')
  if (!parts) return false

  const [, timestamp, signature] = parts
  if (Math.abs(now.getTime() / 1000 - Number(timestamp)) > TOLERANCE) return false

  const received = Buffer.from(signature, 'hex')
  return secrets.some((secret) =>
    timingSafeEqual(received, computeSignature(secret, timestamp, body)),
  )
}

// For keys without a signature: compares without revealing how much matches
export function compareSecrets(received: string, expected: string): boolean {
  const digest = (text: string) => createHash('sha256').update(text).digest()
  return timingSafeEqual(digest(received), digest(expected))
}
  • The raw body is signed, the bytes exactly as they arrived. If you called json() and then JSON.stringify, a space or a different key order would produce another signature. That's why the type is Uint8Array.
  • The timestamp is part of what's signed. Outside the signature, an attacker could change it. The five-minute tolerance allows for slightly out-of-sync clocks.
  • timingSafeEqual compares in constant time. A === stops at the first different character, and by measuring many responses someone could work out a correct signature bit by bit. It requires two values of equal length or it throws an exception; the format guarantees that. compareSecrets achieves it by comparing digests, which always have the same length.
  • Several secrets at once let you rotate them without interrupting the service, as you'll see in section 8.
  • The time is passed in so the function can be tested with fixed dates.

Each provider has its own variant: another header, another separator, base64 instead of hexadecimal. Many publish a library that does it; use it, and make sure you give it the raw body.

// lib/env.ts: in the schema object…
VENUES_SECRET: optional,
VENUES_PREVIOUS_SECRET: optional,
MAIL_URL: optional,
MAIL_KEY: optional,

// …and in the transformation
venuesSecrets: [variables.VENUES_SECRET, variables.VENUES_PREVIOUS_SECRET].filter(
  (secret) => secret !== null,
),
mailUrl: variables.MAIL_URL,
mailKey: variables.MAIL_KEY,
# .env.local (and the same keys, with no value, in .env.example)
VENUES_SECRET=dev-only-secret
MAIL_URL=http://localhost:4001
MAIL_KEY=dev-key

  1. Applying it only once

Providers promise to deliver at least once, never exactly once. If our response gets lost, the notification comes back even though we'd already applied it. We store the identifiers we've seen:

// lib/db/schema.ts (addition)
export const externalNotifications = pgTable(
  'external_notifications',
  {
    id: text('id').primaryKey(),
    type: text('type').notNull(),
    reference: text('reference').notNull(),
    occurredAt: timestamp('occurred_at', { withTimezone: true }).notNull(),
    receivedAt: timestamp('received_at', { withTimezone: true }).notNull().defaultNow(),
  },
  (table) => [index('notifications_type_reference_idx').on(table.type, table.reference)],
)
npm run db:generate -- --name external-notifications
npm run db:migrate

With several providers, the primary key would be (provider, id): two systems can use the same identifier.

Before writing the code, you have to decide what it means for a venue to reduce its capacity when there are already events with bookings:

  • The event can't offer more spots than the venue.
  • Existing bookings aren't canceled automatically. If they already exceed the new capacity, the event becomes fully booked and someone will have to decide.
  • If the capacity increases, nothing is touched: the organizer set their own.
// lib/schemas/notifications.ts
import * as z from 'zod'

const base = {
  id: z.string().min(1).max(100),
  occurredAt: z.iso.datetime({ offset: true }).transform((value) => new Date(value)),
}

// The common part: used to acknowledge types we don't handle
export const envelopeSchema = z.object({ ...base, type: z.string().max(60) })

export const capacityNotificationSchema = z.object({
  ...base,
  type: z.literal('capacity.updated'),
  data: z.object({
    venue: z.string().min(1).max(100),
    capacity: z.number().int().min(1).max(100_000),
  }),
})

export type CapacityNotification = z.output<typeof capacityNotificationSchema>
// lib/data/notifications.ts
import 'server-only'
import { and, eq, gt, sql } from 'drizzle-orm'
import { getDb } from '@/lib/db/client'
import { externalNotifications, events, venues } from '@/lib/db/schema'
import type { CapacityNotification } from '@/lib/schemas/notifications'

export type NotificationResult =
  | { status: 'applied'; adjusted: number; exceeded: number }
  | { status: 'duplicate' | 'outdated' | 'unknown-venue' }

export async function applyCapacityChange(
  notification: CapacityNotification,
): Promise<NotificationResult> {
  const { venue: slug, capacity } = notification.data
  const db = await getDb()

  return db.transaction(async (tx): Promise<NotificationResult> => {
    // 1. Record it. If it was already there, no row is returned
    const [recorded] = await tx
      .insert(externalNotifications)
      .values({
        id: notification.id,
        type: notification.type,
        reference: slug,
        occurredAt: notification.occurredAt,
      })
      .onConflictDoNothing()
      .returning({ id: externalNotifications.id })
    if (!recorded) return { status: 'duplicate' }

    // 2. Lock the venue: another notification about the same one waits here
    const [venue] = await tx
      .select({ id: venues.id })
      .from(venues)
      .where(eq(venues.slug, slug))
      .for('update')
    if (!venue) return { status: 'unknown-venue' }

    // 3. Is there a more recent one?
    const [later] = await tx
      .select({ id: externalNotifications.id })
      .from(externalNotifications)
      .where(
        and(
          eq(externalNotifications.type, notification.type),
          eq(externalNotifications.reference, slug),
          gt(externalNotifications.occurredAt, notification.occurredAt),
        ),
      )
      .limit(1)
    if (later) return { status: 'outdated' }

    // 4. Apply
    await tx.update(venues).set({ capacity }).where(eq(venues.id, venue.id))
    const adjusted = await tx
      .update(events)
      .set({
        capacity: sql`greatest(${events.capacity} - ${events.spotsLeft}, ${capacity})`,
        spotsLeft: sql`greatest(${events.spotsLeft} - (${events.capacity} - ${capacity}), 0)`,
      })
      .where(
        and(
          eq(events.venueId, venue.id),
          gt(events.capacity, capacity),
          gt(events.endsAt, new Date()),
        ),
      )
      .returning({ capacity: events.capacity })

    return {
      status: 'applied',
      adjusted: adjusted.length,
      exceeded: adjusted.filter((event) => event.capacity > capacity).length,
    }
  })
}
  • Recording and applying go in the same transaction. If applying fails, the record is rolled back and the retry will try again. In separate transactions, a failure between the two would leave a notification "seen" and never applied.
  • onConflictDoNothing is the check. Two simultaneous deliveries of the same notification can't both insert: the second waits for the first and gets no row. A prior SELECT would leave a gap between looking and writing.
  • Locking the venue orders concurrent notifications. With it, by the time the second one reaches step 3, it already sees what the first one committed.
  • capacity - spots_left is the number of booked spots. The event's new capacity is the larger of that and the one reported. In an UPDATE, the expressions on the right use the old values, so the order doesn't matter.
  • It doesn't clash with bookings. The events UPDATE waits for any createBooking transactions in progress, and vice versa.
// lib/revalidation.ts (addition) — from Route Handlers
export function notifyCapacityChange(venueSlug: string, hasEvents: boolean): void {
  revalidateTag(venueTag(venueSlug), 'max')
  revalidateTag(VENUES_TAG, 'max')
  if (hasEvents) revalidateTag(EVENTS_TAG, 'max')
}

Nobody expects to see this change instantly, so 'max' is the right choice. The venue tag reaches its page and its events' pages, which have carried it since 05-03. updateTag isn't available in a Route Handler.

  1. The endpoint

// app/api/webhooks/venues/route.ts
import { guarded, errorResponse } from '@/lib/api/responses'
import { applyCapacityChange } from '@/lib/data/notifications'
import { readEnv } from '@/lib/env'
import { capacityNotificationSchema, envelopeSchema } from '@/lib/schemas/notifications'
import { notifyCapacityChange } from '@/lib/revalidation'
import { verifySignature } from '@/lib/security/signatures'

const MAX_SIZE = 32 * 1024

function acknowledge(): Response {
  return new Response(null, { status: 204 })
}

export async function POST(request: Request) {
  return guarded(async () => {
    const { venuesSecrets } = readEnv()
    if (venuesSecrets.length === 0) {
      return errorResponse('unavailable', 'Integration not configured.')
    }

    // 1. The raw body
    const body = Buffer.from(await request.arrayBuffer())
    if (body.byteLength > MAX_SIZE) {
      return errorResponse('too-large', 'The notification is too large.')
    }

    // 2. The signature, before parsing anything
    const signature = request.headers.get('x-venues-signature')
    if (!verifySignature(signature, body, venuesSecrets, new Date())) {
      return errorResponse('unauthorized', 'Invalid signature.')
    }

    // 3. The shape
    let content: unknown
    try {
      content = JSON.parse(body.toString('utf8'))
    } catch {
      return errorResponse('bad-request', 'The body is not JSON.')
    }
    const envelope = envelopeSchema.safeParse(content)
    if (!envelope.success) return errorResponse('invalid-data', 'Incomplete notification.')
    if (envelope.data.type !== 'capacity.updated') return acknowledge()

    const notification = capacityNotificationSchema.safeParse(content)
    if (!notification.success) return errorResponse('invalid-data', 'Invalid capacity data.')

    // 4. Apply, only once
    const result = await applyCapacityChange(notification.data)
    console.info('Venue notification', { id: notification.data.id, ...result })

    if (result.status === 'applied') {
      notifyCapacityChange(notification.data.data.venue, result.adjusted > 0)
    }
    return acknowledge()
  })
}

The order is deliberate: nothing is parsed until the signature is valid, because parsing means exposing code to a stranger.

Situation Response Why
Applied 204
Duplicate or outdated 204 It's already as it should be: stop sending it
Unknown type 204 A new type from the provider isn't their mistake
Unknown venue 204 and a log entry Retrying won't fix it; someone needs to look at it
Wrong signature 401 With a message that doesn't explain what failed
Malformed data 400 or 422 The sender has a bug
The database doesn't respond 500, from guarded Let it retry
Maintenance 503, from the proxy Let it retry

The 204 after the transaction gives a simple guarantee: if the sender gets it, the change is saved. It's just a few queries, well within any sender's time limit. If you had to generate documents or call other systems, you'd store the notification, answer, and do the work afterwards (07-04).

4.1. Trying it out

// scripts/send-notification.mjs — plays the role of the venues' system
import { createHmac, randomUUID } from 'node:crypto'

const [venue = 'the-factory', capacity = '60', id = `ntf_${randomUUID()}`] = process.argv.slice(2)
const secret = process.env.VENUES_SECRET ?? 'dev-only-secret'

const body = JSON.stringify({
  id,
  type: 'capacity.updated',
  occurredAt: new Date().toISOString(),
  data: { venue, capacity: Number(capacity) },
})
const timestamp = Math.floor(Date.now() / 1000)
const signature = createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')

const response = await fetch('http://localhost:3000/api/webhooks/venues', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-Venues-Signature': `t=${timestamp},v1=${signature}` },
  body,
})
console.log(response.status, await response.text())
node scripts/send-notification.mjs the-factory 60 ntf_1     # 204: applied
node scripts/send-notification.mjs the-factory 60 ntf_1     # 204: duplicate
VENUES_SECRET=other node scripts/send-notification.mjs      # 401

Check the capacities with npm run db:studio and the Next.js terminal. A real provider can't call localhost; during development, a temporary tunnel is used, and only with test data.

  1. When there's no signature

Some senders can only send a fixed key in a header. It's weaker: anyone who sees it once can use it forever, with any content. If there's no alternative, make it long and random, in the Authorization header and never in the URL, which ends up in the logs. And compare it with compareSecrets. The revalidation endpoint you tried out in 05-04 becomes this:

// lib/security/bearer-key.ts
import 'server-only'
import { compareSecrets } from '@/lib/security/signatures'

// With no key configured, nobody is accepted
export function hasBearerKey(request: Request, expected: string | null): boolean {
  if (!expected) return false
  const received = /^Bearer (.+)$/.exec(request.headers.get('authorization') ?? '')?.[1]
  return received !== undefined && compareSecrets(received, expected)
}

The first line avoids a well-known flaw: with the variable undefined, comparing against undefined or against the empty string can end up accepting anyone.

As for what to revalidate, two rules. The sender shouldn't choose the tag freely: it's translated from their vocabulary into ours, as notifyCapacityChange does. And the choice between 'max' and { expire: 0 } depends on how serious it is: an ordinary change can tolerate serving the old version once more; withdrawing wrong content can't.

  1. Calling others: retrying properly

Now we switch sides. In 04-01 we didn't retry, because there was a visitor waiting. To send a confirmation email after responding, we do: a transient failure shouldn't leave someone without their message. Retrying badly, on the other hand, makes outages worse: a thousand clients repeating at the same time finish off a service that was recovering.

Question Answer
What gets retried? Network failures, timeouts, 408, 429 and transient 5xx. A 400 or a 401 will fail the same way
How long do you wait? Twice as long each time (exponential backoff), up to a cap
Why random? So clients don't all come back at the same moment (jitter)
What if the service says how long? Retry-After is respected
Until when? A number of attempts and a total deadline
Is it safe to repeat? Only if the operation is idempotent
// lib/http/retries.ts
import 'server-only'
import { setTimeout as wait } from 'node:timers/promises'

const RETRYABLE = new Set([408, 429, 500, 502, 503, 504])

const POLICY = {
  attempts: 4,
  baseDelay: 500,
  maxDelay: 8_000,
  timeout: 5_000, // Per attempt
  totalTime: 20_000, // In total
}

type Options = Omit<RequestInit, 'body' | 'signal'> & { body?: string }

function computeDelay(attempt: number): number {
  const cap = Math.min(POLICY.maxDelay, POLICY.baseDelay * 2 ** (attempt - 1))
  return Math.random() * cap
}

// Seconds, or an HTTP date
function parseRetryAfter(value: string | null): number | null {
  if (!value) return null
  const seconds = Number(value)
  const delay = Number.isNaN(seconds) ? Date.parse(value) - Date.now() : seconds * 1000
  return Number.isFinite(delay) && delay >= 0 ? delay : null
}

// Don't use it during a render: it can take up to the full deadline
export async function fetchWithRetries(url: URL, options: Options): Promise<Response> {
  const deadline = Date.now() + POLICY.totalTime

  for (let attempt = 1; ; attempt++) {
    let delay = computeDelay(attempt)
    let reason: unknown

    try {
      const response = await fetch(url, {
        ...options,
        redirect: 'error',
        signal: AbortSignal.timeout(POLICY.timeout),
      })
      if (!RETRYABLE.has(response.status)) return response

      delay = parseRetryAfter(response.headers.get('retry-after')) ?? delay
      reason = new Error(`Response ${response.status}`)
      await response.body?.cancel() // Frees the connection
    } catch (error) {
      reason = error
    }

    if (attempt >= POLICY.attempts || Date.now() + delay > deadline) {
      throw new Error(`No useful response from ${url.host} after ${attempt} attempts`, {
        cause: reason,
      })
    }
    await wait(delay)
  }
}
  • It also returns 4xx responses: whether they're an error is up to the caller. It only throws when patience runs out.
  • If Retry-After goes past the deadline, it gives up. Waiting two minutes inside a function is a way of blocking it; that's a job for a queue (07-04).
  • body only accepts text. A stream is consumed on the first attempt.
  • redirect: 'error': if the destination sent us somewhere else, we don't want the key to follow it. The URL always comes from our configuration; never call an address received in a webhook or a form.
  • The message includes the host, not the full URL, which could contain data.

When a service has been down for minutes, even the first attempt is wasted. A circuit breaker remembers the latest failures and stops calling for a while. With a single provider and background work we don't need one; in a high-traffic render we would, and it's best to use a library.

  1. The mail service

Repeating a POST that sends an email can send two. The solution mirrors the one for our webhook: we send an idempotency key, and the provider recognizes the repetition. It must come from the business fact ("confirmation of booking X"), not from randomness; if it were generated on every call, it wouldn't recognize anything.

// lib/mail.ts
import 'server-only'
import { readEnv } from '@/lib/env'
import { fetchWithRetries } from '@/lib/http/retries'

export interface Email {
  to: string
  subject: string
  text: string
  key: string // Idempotency key: the same one for the same fact
}

export type EmailResult =
  | { status: 'accepted' }
  | { status: 'not-configured' }
  | { status: 'rejected'; code: number }
  | { status: 'error' }

export async function sendEmail(email: Email): Promise<EmailResult> {
  const { mailUrl, mailKey } = readEnv()
  if (!mailUrl || !mailKey) return { status: 'not-configured' }

  const { key, ...message } = email
  try {
    const response = await fetchWithRetries(new URL('/v1/messages', mailUrl), {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${mailKey}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': key,
      },
      body: JSON.stringify(message),
    })
    await response.body?.cancel()

    if (response.ok) return { status: 'accepted' }
    console.error(`Email ${key} rejected with ${response.status}`)
    return { status: 'rejected', code: response.status }
  } catch (error) {
    console.error(`Could not send email ${key}:`, error)
    return { status: 'error' }
  }
}
// scripts/mail-api.mjs — simulates the service. FAILURES=2 makes the first two calls fail
import { createServer } from 'node:http'

let failures = Number(process.env.FAILURES ?? 0)
const seen = new Set()

createServer(async (request, response) => {
  let body = ''
  for await (const chunk of request) body += chunk

  function send(code, data) {
    console.log(code, request.method, request.url)
    response.writeHead(code, { 'Content-Type': 'application/json' })
    response.end(JSON.stringify(data))
  }

  if (request.method !== 'POST' || request.url !== '/v1/messages') return send(404, {})
  if (request.headers.authorization !== 'Bearer dev-key') return send(401, {})
  if (failures-- > 0) return send(503, {})

  const key = request.headers['idempotency-key']
  if (!seen.has(key)) {
    seen.add(key)
    console.log(JSON.parse(body))
  }
  send(202, { accepted: true })
}).listen(4001, () => console.log('Mail API at http://localhost:4001'))

accepted means the service has taken charge of it, not that the person has received it. The logs carry the key and not the address, which is personal data. And notice the shape: an interface of our own, sendEmail, behind which any provider could sit. We'll use it in the next lesson.

7.1. Rate limits

A provider allows a certain number of requests per second or per month. When sending many, you have to spread them out: one at a time, or in small groups with Promise.allSettled, never Promise.all over a thousand items. A 429 with Retry-After is their way of asking you to calm down.

And we're a provider for others too. Our v1 API must also be able to say "enough":

Where it's counted What it's for
Load balancer, CDN or platform Stopping volume before it reaches Node. It comes first
Process memory A single server; each instance counts on its own and resets on restart
Shared store Per-client or per-account limits that need to be exact

What you can't do is limit by IP carelessly (04-05). You'll practice it in exercise 3, and 08-02 will apply it to sign-in attempts.

  1. Secrets

There are already four: the database, the weather, the venues and the mail; more will come. Common rules:

  • Only in server environment variables, never with NEXT_PUBLIC_, and declared in lib/env.ts.
  • One per integration and per environment. If the test one leaks, production isn't affected.
  • Never in URLs, logs or error messages.
  • With a plan for rotating them. With a single active secret, rotating it interrupts the service until both sides match. With two: you put the new one in VENUES_SECRET and the old one in VENUES_PREVIOUS_SECRET; you update the sender; when there are no old deliveries left, you empty the second one.
  • If it leaks, rotate it right away. Deleting it from the repository isn't enough: it's still in the history.

Common Mistakes and Tips

  • Computing the signature over rebuilt JSON.
  • Comparing signatures or keys with ===.
  • Accepting everyone when the secret is missing.
  • Responding 200 to any error. The notification is lost.
  • Responding with a 4xx to an unknown type or a duplicate. Some senders end up disabling the webhook.
  • Recording the identifier outside the transaction.
  • Assuming they arrive in order.
  • Retrying during a render, or without a total deadline, or retrying a 400.
  • A random idempotency key on every attempt.
  • Calling a URL received in the body.
  • Logging the whole body. It may contain personal data.

Exercises

Exercise 1: reviewing a webhook

Find the problems in this code.

export async function POST(request: Request) {
  const notification = await request.json()
  const signature = createHmac('sha256', process.env.SECRET ?? '')
    .update(JSON.stringify(notification))
    .digest('hex')
  if (signature !== request.headers.get('x-signature')) {
    return Response.json({ error: `Expected ${signature}` }, { status: 401 })
  }
  try {
    await changeCapacity(notification.data.venue, notification.data.capacity)
    await emailEveryone(notification)
  } catch (error) {
    console.error(error, notification)
  }
  return Response.json({ ok: true })
}

Solution

  1. It parses before verifying, and it signs rebuilt text.
  2. Without SECRET, the key is the empty string, which anyone knows.
  3. It compares with !==.
  4. The 401 response hands over the correct signature for that body.
  5. No timestamp: it can be resent forever.
  6. No identifier: every repetition sends the emails again.
  7. It doesn't validate data.
  8. The emails are sent before answering; if the sender gets tired of waiting, it will try again.
  9. On failure it responds 200, and it logs the entire content as well.
  10. It doesn't revalidate anything.

Exercise 2: remote revalidation

The city council team has a tool that fixes data directly in the database and wants to notify AgendaViva. Create POST /api/revalidate, with a key in Authorization, that receives { "type": "event" | "venue", "slug": "…", "urgent": true }. Reuse what already exists.

Solution

// app/api/revalidate/route.ts (REVALIDATION_KEY: optional in lib/env.ts → revalidationKey)
import { revalidateTag } from 'next/cache'
import * as z from 'zod'
import { readJson } from '@/lib/api/body'
import { guarded, errorResponse } from '@/lib/api/responses'
import { readEnv } from '@/lib/env'
import {
  EVENTS_TAG, VENUES_TAG, eventTag, venueTag,
} from '@/lib/tags'
import { hasBearerKey } from '@/lib/security/bearer-key'

const schema = z.object({
  type: z.enum(['event', 'venue']),
  slug: z.string().min(1).max(140),
  urgent: z.boolean().default(false),
})

export async function POST(request: Request) {
  return guarded(async () => {
    if (!hasBearerKey(request, readEnv().revalidationKey)) {
      return errorResponse('unauthorized', 'Invalid key.')
    }
    const body = await readJson(request, schema)
    if (!body.valid) return body.response

    const { type, slug, urgent } = body.data
    const patience = urgent ? { expire: 0 } : 'max'
    const tags =
      type === 'event'
        ? [eventTag(slug), EVENTS_TAG]
        : [venueTag(slug), VENUES_TAG]

    for (const tag of tags) revalidateTag(tag, patience)
    return new Response(null, { status: 204 })
  })
}

The key is checked before reading the body. The sender says what changed, not which tag to invalidate. Repeating it does no harm, so it doesn't need identifiers. It's a practice exercise: the project doesn't keep it.

Exercise 3: saying enough

Write consume(key, max, windowMs, now), which keeps an in-memory counter per key and window, and returns the milliseconds remaining if the maximum has been exceeded, or 0 if the request is allowed. Use it in an endpoint that responds with 429. What limitations does it have?

Solution

// Practice only
const counters = new Map<string, { uses: number; expires: number }>()

export function consume(
  key: string,
  max: number,
  windowMs: number,
  now: number,
): number {
  if (counters.size > 10_000) {
    for (const [other, { expires }] of counters) if (expires <= now) counters.delete(other)
  }

  const current = counters.get(key)
  if (!current || current.expires <= now) {
    counters.set(key, { uses: 1, expires: now + windowMs })
    return 0
  }
  current.uses++
  return current.uses > max ? current.expires - now : 0
}

// In a Route Handler
const remaining = consume('availability', 100, 60_000, Date.now())
if (remaining > 0) {
  return errorResponse('too-many-requests', 'Too many requests.', {
    headers: { 'Retry-After': String(Math.ceil(remaining / 1000)) },
  })
}

Each process counts on its own and loses the count when it restarts. At the window boundary, up to twice as many requests can get through in a row. Without the cleanup, the map would grow forever. With a global key, one abuser uses up everyone's quota; with the IP, you need to know where it comes from (04-05). For anything important, use the platform or a shared store.

Conclusion

Receiving a webhook means reading the raw body, verifying a timestamped signature in constant time, validating, applying it only once inside a transaction and answering with the status code the sender needs. Calling others means accepting that they'll fail: a limit per attempt and for the whole operation, randomized backoff, Retry-After and an idempotency key that makes repetition harmless. AgendaViva now adjusts its events' capacity when the venues report changes, and it has a reliable mail client.

That client can take twenty seconds to give up, and nobody should have to wait that long to see their booking confirmed. We need a place for work that starts once the response has already gone out: Post-Response Work with after.

© Copyright 2026. All rights reserved