Smart Parcel Cubby Network: Reservations and Offline Kiosks
System DesignModel answerLast updated
Design a backend for networked parcel cubbies in three sizes, preventing double booking of the last cubby and staying consistent when kiosks lose connectivity.
Design a Parcel Cubby Network
A company operates self-service parcel cubbies installed in places like residential buildings and train stations. Each site has a kiosk that controls a bank of cubbies in three sizes: Small, Medium and Large. You are asked to design the backend that lets people hold a cubby, leave a parcel in it, and collect it later.
What the service must do
- Show how many cubbies of each size are free at a given site.
- Let a user place a time-limited hold on one cubby of a chosen size.
- Track every cubby as
EMPTY,RESERVEDorOCCUPIED. - Handle drop-off (
RESERVEDtoOCCUPIED) and pickup (the cubby returns to being free).
Quality requirements
- No double booking: two users must never end up holding the same cubby, even when they compete for the last one of a size.
- Scale: thousands of sites worldwide.
- Availability under flaky links: a hold should still be granted when the site's kiosk is temporarily offline, and the cubby state must stay consistent once it reconnects.
What to cover
- API: the main endpoints for checking availability, reserving, and confirming drop-off (and pickup).
- Data model: tables or entities for sites, cubbies and bookings.
- Concurrency control: how you prevent races when many users go for the final free cubby of one size.
- Architecture: a high-level design that connects the central service with the distributed kiosks.
State your assumptions about traffic, hold duration and who initiates reservations, and call out the trade-offs you are making.
Hints
Hint 1
Estimate load before designing: millions of holds per day is only hundreds of writes per second at peak. Which parts of the problem are actually hard, then?
Hint 2
Consider keeping two records: one for the cubby's current state and one for the booking's lifecycle and history. What does each make easy or hard (finding a free cubby, expiry, auditing)?
Hint 3
All contention is inside a single site. How does that influence your choice of shard key, and which database mechanisms (row locks with skip-locked, conditional updates, unique constraints) can guarantee only one winner?
Hint 4
Decide who is the authority for what: the cloud for bookings, the kiosk for physical door state. What lets a kiosk open the right door while it is offline, and how do you replay its events safely afterwards?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This looks like CRUD but really tests two things: mutual exclusion on a scarce resource and reconciling a central source of truth with unreliable edge devices. Throughput is modest, so spend your time on correctness.
1. Assumptions and scale
- About 10,000 sites with ~100 cubbies each, so ~1M cubbies.
- ~3M holds per day: ~35 writes/s average, ~350/s at peak (10x).
- Availability reads are 10-20x writes: ~5K QPS at peak.
- Hold duration is configurable per site (e.g. 15-30 min for self-service, 24-72 h for carrier deliveries).
- Holds are made through an app or partner API. The kiosk only performs physical actions: open a door, sense a parcel.
Conclusion to say out loud: a single sharded relational database is plenty. The difficulty is contention and partial connectivity, not volume.
2. API
GET /sites/{siteId}/availability
-> { "SMALL": 12, "MEDIUM": 3, "LARGE": 0 }
POST /sites/{siteId}/holds (Idempotency-Key header)
{ size, userId, durationMins }
-> 201 { holdId, cubbyId, accessToken, expiresAt }
-> 409 NO_CAPACITY
POST /holds/{id}/dropoff (kiosk) { accessToken, kioskEventId, occurredAt }
POST /holds/{id}/pickup (kiosk) { pickupCode, kioskEventId, occurredAt }
DELETE /holds/{id} (user cancels)
POST /kiosks/{id}/events:batch (offline replay)
GET /kiosks/{id}/sync?since=cursor (pull new holds)
Every mutating call is idempotent: client calls use an idempotency key, kiosk calls use a unique kioskEventId. Retries and replays are therefore safe.
3. Data model
Keep two records. The cubby row holds current state; the booking row holds lifecycle and history. A state column alone loses history and makes expiry/audit awkward; a bookings table alone makes "find a free cubby" an anti-join.
sites(site_id PK, region, timezone, kiosk_id, status)
cubbies(cubby_id PK, site_id, size, state, -- EMPTY|RESERVED|OCCUPIED|OUT_OF_SERVICE
current_hold_id, version, updated_at)
INDEX (site_id, size, state)
holds(hold_id PK, site_id, cubby_id, user_id,
status, -- RESERVED|OCCUPIED|COMPLETED|EXPIRED|CANCELLED
access_code_hash, pickup_code_hash,
reserved_at, expires_at, dropped_at, picked_at, version)
UNIQUE (cubby_id) WHERE status IN ('RESERVED','OCCUPIED')
INDEX (status, expires_at)
kiosk_events(kiosk_event_id PK, kiosk_id, type, payload, occurred_at, applied_at)
The partial unique index is a database-level guarantee that a cubby never has two active holds, a safety net against application bugs.
4. Concurrency: the last-cubby race
Run allocation as one transaction on the site's shard.
Option A, pessimistic with SKIP LOCKED (preferred on a relational DB):
BEGIN;
SELECT cubby_id FROM cubbies
WHERE site_id=$1 AND size=$2 AND state='EMPTY'
LIMIT 1 FOR UPDATE SKIP LOCKED;
-- no row -> ROLLBACK, return 409
UPDATE cubbies SET state='RESERVED', current_hold_id=$h, version=version+1
WHERE cubby_id=$c;
INSERT INTO holds (...) VALUES (...);
COMMIT;
Concurrent requests lock different empty cubbies instead of queueing on one row. When only one cubby remains, one request wins and the rest find nothing and get a clean 409.
Option B, optimistic conditional update:
UPDATE cubbies SET state='RESERVED', version=version+1, current_hold_id=$h
WHERE cubby_id=$c AND state='EMPTY' AND version=$v;
Zero rows affected means someone else won; pick another candidate and retry. Lock-free and a natural fit for stores with conditional writes (e.g. DynamoDB), but it can produce retry storms at hot sites.
Trade-off: SKIP LOCKED behaves better under contention; OCC is simpler on key-value stores. Do not use a distributed lock (e.g. Redis) for correctness. The database transaction is the source of truth; Redis only caches counts.
5. Architecture
Apps / Partner APIs -> API Gateway -> Hold Service -> Postgres (sharded by site_id)
| transactional outbox -> Kafka
v
Kiosk Sync Service <-> Kiosks (HTTPS/MQTT, local SQLite)
Expiry Worker (scans status, expires_at) Availability cache (Redis, per site/size)
Notification Service (codes, expiry warnings)
- Shard by
site_id: all contention is intra-site, so every allocation is a single-shard transaction and sites spread evenly. - Outbox pattern: each state change writes an event in the same transaction; consumers refresh Redis counts, push to kiosks and send notifications.
- Availability reads come from Redis and may be slightly stale. That can only cause an occasional 409, never a double booking, because the transaction is authoritative.
6. Flaky kiosk connectivity
Split authority:
- The cloud owns holds. Reserving never needs the kiosk online, satisfying the availability requirement.
- The kiosk owns physical truth: door and sensor state.
Mechanisms:
- Signed access tokens. The cloud signs
(holdId, cubbyId, expiresAt)with a per-kiosk key. Even if the kiosk missed the sync, it can verify signature and expiry locally and open the correct door. - Local durable event journal. Drop-offs and pickups get a monotonic sequence number and are replayed via
events:batchon reconnect, applied idempotently bykioskEventId. - Conflict rules. Physical events win. The kiosk refuses to open after token expiry, which bounds the conflict window. The server releases a hold only after
expires_at + grace(e.g. 10 min) to absorb clock skew and replay lag.
7. Expiry, no-shows and recovery
- An expiry worker scans
(status, expires_at), moves overdueRESERVEDholds toEXPIRED, and frees the cubby in one transaction. Make it idempotent and safe to run in parallel withSKIP LOCKED. - For an
OCCUPIEDhold past its deadline, do not auto-free; flag it for staff or a return flow, since a parcel is physically inside. - On kiosk reboot or reconnect, reconcile: the kiosk reports sensor state per door; discrepancies (cubby
EMPTYin the DB but sensor says occupied) mark itOUT_OF_SERVICEand raise an alert.
Common mistakes
- Using only a state flag and no booking record, losing history and complicating expiry.
- Doing "check availability, then reserve" as two separate steps, which creates a race.
- Relying on a cache or distributed lock for correctness.
- Requiring the kiosk to be online to create a hold.
- Freeing expired holds immediately, ignoring clock skew and delayed replays.
- Over-engineering for scale (global consensus, multi-region writes) when per-site sharding suffices.
Extensions worth mentioning
Multi-size fallback (offer a larger cubby if the requested size is full), overbooking policies, per-site hold limits, rate limiting to stop users hoarding cubbies, and multi-region deployment with each site homed in one region.