system designs

Amazon Lockers

5 deep dives · 3 follow-ups · updated Oct 15, 2026

1. Functional requirements

  1. Select a nearby locker at checkout, by location, hours and compartment size.
  2. Deliver: the courier opens a compartment, drops the package, confirms; the customer gets a pickup code.
  3. Pick up: the customer enters the code at the locker and the compartment opens.

Assumption: selecting reserves capacity for a size class at the locker, not a specific door.

Below the line: expirations and returns, notification channels, QR and OTP variants, courier routing, operator admin, overbooking policy.

Scale: 1M compartments across 10K locations; 5M packages a day, about 60 reservations/s, 300/s peak; searches ~10x that. Throughput is small. The design is driven by per-locker capacity contention and locker devices with intermittent connectivity.

2. Non-functional requirements

  1. Consistency for reservations: no over-allocating a locker
  2. Pickup works offline: the locker validates locally, door opens in under 1 s
  3. Secure codes: single use, one locker, expiring
  4. Delivery workflow never loses a step or runs one twice

3. Core entities

  • Customers
  • Delivery agents
  • Orders
  • Lockers
  • Compartments
  • Reservations: reserved → delivered → picked_up | expired
  • Pickup codes

4. API routes

Auth is a header on all four: customer, courier or device. Simple enough to start; the offline deep dive turns pickup from a question into a report.

Search
GET /lockers/search
params: lat, lng, size, radius
returns: Locker[] with free count per size

Reserve
POST /reservations            Idempotency-Key: orderId
body: orderId, lockerId, size
returns: reservationId

Deliver
POST /reservations/:reservationId/deliver    Idempotency-Key: reservationId
body: compartmentId
returns: ok, pickup code sent to the customer

Pickup
POST /lockers/:lockerId/pickup    device auth
body: code
returns: compartmentId to open

5. High-level design

The simplest system that satisfies the four routes. Three clients, one gateway, a locker service for reads and a reservation service for the lifecycle, one database. The deep dives change this picture.

Boxes, drawing order: customer app, courier handheld, locker device · gateway · locker service, reservation service · Postgres · notification service beside reservations.

High-level design

Data model:

Locker        id, lat, lng, hours
Compartment   id, lockerId, size, status
Reservation   id, orderId, lockerId, size, compartmentId, status
PickupCode    reservationId, code, expiresAt, usedAt

Postgres, one primary: transactions for capacity and for the delivery state change, unique on orderId for retries. 60 writes/s needs nothing more.

6. Deep dives

Order in the room: 6.1 must · 6.2 if time · 6.3, 6.4, 6.5 one line each, only if asked. Each deep dive opens with three spoken sentences: Problem, Pick, Cost. Everything under them is what you say when the interviewer digs.

6.1 No over-allocation: a capacity counter per size

Problem. Reserve counts free compartments minus active reservations, then inserts; two checkouts for the last slot read the same count and both insert. Pick. A capacity row per locker and size, locker_capacity(lockerId, size, total, reserved), reserved with one conditional update, reserved + 1 where reserved < total; 0 rows means 409 and the next locker. Cost. A serialization point per locker and size, cold at 500 writes a day, and a sweeper to release expired holds. Rejected: a lock per compartment, because the customer buys a size class, not a door.

Draw: a locker_capacity table beside Reservations and a sweeper.

6.1 Reservation consistency

Flow

  1. Reserve: UPDATE locker_capacity SET reserved = reserved + 1 WHERE lockerId = ? AND size = ? AND reserved < total. 0 rows → 409, the client offers the next locker; 1 row → insert the reservation as reserved, expiresAt = now + 7 days, same transaction.
  2. Race: the second UPDATE waits on the row lock, then re-checks reserved < total against the committed value.
  3. Idempotency: reservation.orderId is unique, so a retried checkout rolls back with the counter untouched and returns the existing reservationId.
  4. Release: pickup sets picked_up and reserved - 1 in one transaction. A sweeper runs every minute: reserved past expiresAt → expired, reserved - 1.

Follow up: capacity is held from checkout until pickup, up to a week. How do you keep lockers from sitting reserved but empty?

Answer: The empty window is checkout to delivery, one or two days; after that the compartment is physically full. Overbook: the bound becomes reserved < total × 1.1, sized from the measured rate of expired and cancelled reservations. A courier who finds the cabinet full is redirected by the handheld to the nearest locker with space, and the customer gets a new code. Or reserve late: hold at checkout only until the order ships, then run the same UPDATE at dispatch with the real ETA and a short expiry. Overbooking is the smaller change and matches how the business already treats delivery promises.

6.2 Pickup offline: the device validates locally

Problem. The code is validated in the reservation service, so a locker with no link cannot open a door while the customer stands at the keypad. Pick. Codes are pushed to the locker on deliver and derivable there as HMAC(deviceSecret, reservationId), so the device validates from local storage, opens in under a second, queues the open and syncs when the link returns, deduped by eventId. Cost. The backend learns about opens late, and a per-device secret to protect. Rejected: validation in the backend, because the link is exactly what fails.

Draw: the device gets local storage and a queue; the pickup route becomes a codes pull and an events upload.

Routes (replace POST /lockers/:lockerId/pickup from section 4; the device no longer asks, it reports):

// Device gateway → locker over MQTT on deliver; the locker pulls on reconnect
GET  /lockers/:lockerId/codes?since={cursor} → [{ reservationId, compartmentId, code, expiresAt }]

// Locker → backend, batched on reconnect, idempotent on eventId
POST /lockers/:lockerId/events [{ eventId, type: delivered | opened | denied, reservationId, compartmentId, at }] → ok

6.2 Offline pickup

Flow

  1. Deliver: the courier scans the signed package label at the cabinet; the device opens a free door of that size and stores {reservationId, compartmentId}. The handheld posts deliver over cellular; the backend sends the customer the code and pushes {reservationId, compartmentId, code, expiresAt} to the device over MQTT.
  2. Push never arrived: the device derives HMAC(deviceSecret, reservationId) for the entry it stored at delivery, the same code the customer received.
  3. Pickup: keypad → local SQLite lookup (code, usedAt, expiresAt) → open the door → mark used, queue opened(eventId, reservationId, compartmentId, at).
  4. Sync: on reconnect the device pulls codes?since=cursor and drains its queue to POST /events. The Reservation service reconciles: picked_up, compartment free, reserved - 1; eventId is unique, so a redelivered batch is a no-op.

Follow up: the locker is offline when the courier arrives. How does the courier get in, and how does the customer still get a code?

Answer: The courier never needs the backend at the cabinet. The label carries a token signed at dispatch (reservationId, lockerId, size, expiry); the device verifies it with the backend’s public key and opens a free door. The handheld has its own cellular link, so deliver reaches the backend, which derives the same HMAC code and sends it to the customer. If the handheld is offline too, the customer is notified when either device syncs, since both report delivered and the notification is idempotent on reservationId. The only thing lost while offline is a remote door open for support, which waits for reconnect.

6.3 Secure codes

Problem. A stored code with an expiry and nothing else: no attempt limit, no binding to the locker, and after 6.2 the device is all that stands between a guess and a door. Pick. Eight digits derived per device, bound to one reservation and one locker, single use, three-day expiry, a keypad lockout that doubles after five failures, every open and denial in an append-only audit log. Cost. One fixed code per reservation and support tooling for disputes.

6.3 Secure codes

Problem. Every door open is a round trip over a flaky link, and search scans 10K lockers counting compartments on the fly. Pick. Nothing on the network before the door moves, and search through a PostGIS geo index with free counts cached in Redis for 30 s. Cost. Counts up to 30 s stale; a 409 at checkout sends the customer to the next locker in the list.

6.4 Low latency

6.5 Durable delivery: transactional outbox

Problem. Deliver commits, then calls the notification service; a crash in between loses the code, a retry texts it twice, a provider outage fails the courier. Pick. The state change and the intent to notify commit together in an outbox row; a relay publishes to Kafka and an idempotent consumer sends, deduped by reservationId. Cost. At-least-once delivery absorbed by the consumer, and a relay to operate; the courier’s call never waits on a provider.

6.5 Durable delivery workflow

Final design

Final design

Trade-offs, the two to say:

  • A capacity counter over per-compartment locks: the customer buys a size class, not a door; one conditional update on a cold row lets the courier take any free door.
  • Validation on the device over the backend: pickup must work with no link; the price is a backend that learns about opens late and a per-device secret to protect.

Study only, not for the room: full flows for 6.3, 6.4 and 6.5, and the 6.5 follow-up.

6.3 flow

  1. Issue: on deliver, code = HMAC(deviceSecret, reservationId) truncated to 8 digits, stored in pickup_code(reservationId, code, expiresAt, usedAt). The secret is per device, so the code works at one locker only.
  2. Validate on the device: an entry exists for this code, usedAt is null, now < expiresAt (delivery + 3 days).
  3. Single use: the device sets usedAt before the latch fires and the opened event sets it on the backend. Lockout: 5 failed tries lock the keypad for 15 minutes, doubling each time, counted per locker.
  4. Audit: every open and denial lands in locker_event(eventId, lockerId, compartmentId, reservationId, type, at), append-only. Support can trace a dispute, and a spike of denials at one locker pages someone.

6.4 flow

  1. Door: keypad → SQLite lookup by code, under 10 ms → latch opens → event queued. The link is never on the path.
  2. Search: GET /lockers?lat,lng,size,radius → Locker service → WHERE ST_DWithin(geom, point, radius) AND open_now ORDER BY distance LIMIT 20, GiST index on geom.
  3. Availability: MGET avail:{lockerId}:{size} for the 20 results; miss → total - reserved from locker_capacity, SETEX … 30. Drop the full ones.
  4. Staleness: 30 s of stale counts is fine because reserve is the source of truth; a 409 at checkout sends the customer to the next locker in the list.

6.5 flow and follow-up

  1. Deliver: one transaction: reservation → delivered, compartment → occupied, insert pickup_code, insert outbox(id, type: delivered, reservationId, payload). Idempotency-Key = reservationId: a retry finds the reservation already delivered and returns ok with no second outbox row.
  2. Relay: a poller or Debezium CDC publishes each outbox row to Kafka reservation-events, key = reservationId, then marks it sent. A crash between the two republishes: at least once, in order per reservation.
  3. Notify: the consumer claims notification_log(reservationId, type) with a unique insert, sends, then marks it sent. A redelivery skips a sent row; the worst case is one repeated text, never a lost one.
  4. Failure: retries with backoff through a retry topic, then reservation-events.dlq and an alert; an operator replays. The Device gateway consumes the same topic to push the code to the locker.

Follow up: the SMS provider is down for an hour. What does the customer experience?

Answer: Nothing breaks on the courier’s side: deliver committed and the event is sitting in Kafka. The consumer trips a circuit breaker and fails over to a second SMS provider, with app push and email as further channels. Whatever still cannot be sent retries with backoff and lands in the DLQ, and the on-call replays it when the provider recovers. The notification is a nudge, not the source of truth: the order page reads pickup_code from the database, so the app shows the code with no SMS. The outbox turns the outage into a delay, never a loss.