BlogArchitecture

An automatic waitlist with DynamoDB Streams and Lambda

A DynamoDB stream filter runs a Lambda only when a booking is cancelled. It offers the slot to the first person on the waitlist and holds it for 15 minutes.

Ink and watercolor illustration: a shelf of potted plants with one empty gap; from a cart holding three waiting seedlings, the first one jumps toward the gap along a dashed line.

If your bookings live in DynamoDB, you can refill the slots a cancellation leaves without a cron job and without touching your API: turn on the table’s stream, add a filter that only lets through the change from “confirmed” to “cancelled”, and let a Lambda notify the first person on the waitlist. The function only runs when someone cancels.

The problem: the slot nobody sees

In a booking business (a physio clinic, a hair salon, a beauty studio), a cancellation three hours before the appointment usually ends up as an empty slot even when people are waiting for one: nobody finds out in time. Calling the waitlist by hand means someone has to be watching the calendar at that exact moment.

The automatic version has three parts:

  1. Detect the cancellation as soon as it is saved.
  2. Pick the first person on the waitlist for that day.
  3. Offer them the slot and hold it for a few minutes, so nobody else takes it while they read the message.

What DynamoDB Streams and event filtering are

A DynamoDB stream is an ordered log of a table’s changes: every insert, update or delete produces a record. With the NEW_AND_OLD_IMAGES view type, each record carries the item before the change (OldImage) and after it (NewImage).

Lambda reads the stream through an event source mapping, the connector that pulls records and calls your function. It supports event filtering: you define a pattern and Lambda only invokes the function with the records that match. Everything else is discarded before it reaches your code.

According to the AWS tutorial, you can have up to 5 patterns per stream; patterns are combined with a logical OR, and the conditions inside one pattern with an AND. One important limit: there are no numeric comparisons, because DynamoDB sends numbers as strings ("N": "50").

How to set it up

1. The data model. One table, with bookings and the waitlist in each business’s partition:

  • Booking: PK = BUSINESS#123, SK = BOOKING#2026-11-20T10:00#physio-1, with status, date and clientId.
  • Waitlist: PK = BUSINESS#123, SK = WAIT#2026-11-20#2026-11-12T09:14:03Z#cli_42.

Putting the sign-up time in the waitlist key means a prefix query returns whoever signed up first. No extra indexes.

2. The stream. Turn it on with NEW_AND_OLD_IMAGES. Without the old image you cannot tell which status the booking came from.

3. The filter. This pattern only lets through bookings that were confirmed and are now cancelled:

{
  "Filters": [
    {
      "Pattern": "{ \"dynamodb\": { \"NewImage\": { \"status\": { \"S\": [\"cancelled\"] } }, \"OldImage\": { \"status\": { \"S\": [\"confirmed\"] } } } }"
    }
  ]
}

Both conditions sit inside the same dynamodb object, so both must hold. The OldImage condition is the one that matters: without it, any later write to an already cancelled booking (a note, a new reason) would run the function again and notify someone else. Inserts don’t match either, because they have no old image.

4. The function. It finds the first person on the waitlist and marks the slot as offered with a conditional write:

import { DynamoDBClient } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient, QueryCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb';
import { unmarshall } from '@aws-sdk/util-dynamodb';
import type { DynamoDBStreamEvent } from 'aws-lambda';

const db = DynamoDBDocumentClient.from(new DynamoDBClient({}));
const TABLE = process.env.TABLE!;
const HOLD_MINUTES = 15;

export const handler = async (event: DynamoDBStreamEvent) => {
  for (const record of event.Records) {
    const booking = unmarshall(record.dynamodb!.NewImage as any);

    const { Items = [] } = await db.send(new QueryCommand({
      TableName: TABLE,
      KeyConditionExpression: 'PK = :pk AND begins_with(SK, :wait)',
      ExpressionAttributeValues: { ':pk': booking.PK, ':wait': `WAIT#${booking.date}#` },
      Limit: 1,
    }));
    const first = Items[0];
    if (!first) continue; // nobody waiting: the slot goes back to the calendar

    const until = new Date(Date.now() + HOLD_MINUTES * 60_000).toISOString();
    try {
      await db.send(new UpdateCommand({
        TableName: TABLE,
        Key: { PK: booking.PK, SK: booking.SK },
        UpdateExpression: 'SET #s = :offered, offeredTo = :client, heldUntil = :until',
        ConditionExpression: '#s = :cancelled',
        ExpressionAttributeNames: { '#s': 'status' },
        ExpressionAttributeValues: {
          ':offered': 'offered',
          ':client': first.clientId,
          ':until': until,
          ':cancelled': 'cancelled',
        },
      }));
    } catch (e: any) {
      if (e.name === 'ConditionalCheckFailedException') continue; // already offered
      throw e;
    }

    await notify(first.clientId, booking, until); // SMS, WhatsApp or email
  }
};

Three details in this code:

  • The status = cancelled condition protects you from retries. If the Lambda fails after writing, the stream delivers the same record again. The second time the condition fails and the slot is not offered twice. It is the same idea I covered in the post on idempotency in Lambda.
  • There is no loop. The function moves the booking to offered, and that change does not match the filter, so it does not fire again.
  • The notification goes after the write. If sending fails, the retry won’t repeat it because the condition no longer holds. If the message is critical for you, put it on an SQS queue instead of sending it from here.

status is a DynamoDB reserved word, hence the #s alias in the expressions.

5. The expiry. For the 15 minutes you have two options. The simplest: when the client taps the link to confirm, check heldUntil; if they are late, the slot is no longer theirs and goes back to the calendar. The complete one: create a one-time schedule in EventBridge Scheduler for 15 minutes later that passes the slot to the next person. With --action-after-completion DELETE, the schedule deletes itself after it runs.

My take

I would use this in any booking business before a job that checks for cancellations every five minutes. It reacts as soon as the change is saved, adds no code to the API you already have, and the function doesn’t run once on a day when nobody cancels.

I would start with the simple version: expiry checked on confirmation and a single message to the first person on the list. The EventBridge Scheduler chain makes sense once the waitlist regularly has several people per day, and not before.

What I don’t like is debugging filters. If the pattern is wrong, there is no error: the function just doesn’t run, and you find out when a client complains. So I would always add a test that creates a test booking, cancels it and checks that the slot moves to offered. And watch the format: the filter value carries the DynamoDB type ("S"), and if you store status under another name or in capitals, nothing matches.

Sources

If you want to see how I build SaaS on AWS serverless without a team, follow me on LinkedIn.

← All articles

Have a product to build or a tech stack to put in order?

Tell me what you are trying to achieve and where you are today. I reply personally, usually within a day.

Free · 30 minutes

Digital strategy session

30 minutes to map where to start digitalizing and transforming your business. You pay nothing, before or after.

When you book, you answer three short questions: what you need, what stage your project is at and when. That way the session starts with context.