Design a parcel locker
medium 80 minModel a wall of doors where couriers leave parcels and customers collect them with a code.
Video lesson · Chapter 1 of 6
Make a prediction
Parcel locker LLD in 90 seconds
1:30Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A parcel locker in a low-level design round is the software behind a wall of doors. It chooses a door for a parcel, gives the customer a secret that opens exactly this door, and knows when the door can be used again.
Underneath it is a lease: somebody gets the use of a thing, with proof and with an end. Hotel cards, shared bikes, database connections and messages in a queue have the same shape.
What makes it its own problem is the metal. A door is open or shut in the world, and the program learns about it from a wire, late, twice or not at all.
Why it exists
Everybody has seen one, so there is nothing to explain, and the conversation is soon about what happens between two steps.
It shows whether somebody models with yes and no fields or with states. occupied is the natural first idea, and it is not enough.
It brings security into an object design round in a friendly way: randomness, length of a secret, one error text, a limit on mistakes. And it has one lesson that stays: the end of a right and the end of a use are two events.
A short history
2001
Deutsche Post starts Packstation as a pilot in Dortmund and Mainz, on machines built by KEBA from Linz.
2005
RFC 4226 describes one-time passwords from a counter (HOTP), with a throttling rule for short codes. Published in December.
2009
The Integer.pl group introduces InPost lockers in Poland.
2011
RFC 6238 adds time to one-time passwords in May. In September the Amazon Locker programme starts in New York City, Seattle and London.
2016
Python 3.6 brings the
secretsmodule, so that codes are not made withrandom.
Words to know
- Compartment or door
- One box with one lock, a size and a number. This page says door.
- Stay
- The agreement: this parcel, this door, this code, until then. Also called access token or lease.
- Claim
- Find a free door and take it, in one step.
- Loading, emptying
- The door is open: for the courier, or for whoever takes the parcel out.
- Overdue
- The end of the stay has passed and the parcel is still inside.
- Lazy expiry
- Nothing happens at the end. Whoever asks later compares with the clock.
- Idempotent event
- Handling it twice has the same result as once.
- Journal
- What we are about to do, written to disk before we do it.
- Outbox
- Messages stored together with the change they report, and sent afterwards.
- Reconcile
- Compare belief and reality again and again, and act on the difference.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
Solve it like an interview
New to it? Start with Approach. Revising? Go straight to the mock.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Courier deposits. The smallest free door that fits opens
Understand it
Start here
Bread behind doors
The old mill bakes at night. Nobody wants to get up at five to fetch a loaf, so the wall of the mill has five small doors: two small (1 and 2), two medium (3 and 4) and one large (5). Watch what each door is doing, and notice that "taken" is not one thing.
Two events come from software (deposit, pick up). Two come from the world (the door was shut, nobody came). A good design has a place for all four.
What an interviewer looks for here
Do they ask about time?
How long is a code valid, and who empties the door after that? These are two questions.
Do they see four states?
Open for loading and open for emptying are states. A yes or no field loses them.
Where does the code live?
On the stay, not on the door and not on the parcel. Ask who creates it and who ends it.
Is the code worth anything?
Random, unique among the living, used once, hard to guess, one error text.
Questions
Six questions, and what each answer changes
| Ask | If the answer is | Then |
|---|---|---|
| Which sizes? May a small parcel use a larger door? | Three; yes, upwards only | Sizes with an order, and a search that starts at the parcel's own size |
| How does the customer prove themselves? | A code by text message | A Stay that can be found by its code |
| How long is the code valid? | Three days | An end on the stay, and a clock that is passed in |
| What happens after that? | A courier takes the parcel back | overdue and take_back. The door is not free before that |
| Do we know when a door is open or shut? | Yes, there is a sensor | door_shut is an input. Without a sensor you must guess with a timer |
| Is the message our job? Payment? Booking? | A service we call; no; not now | A Notifier with one method; the rest is named and left out |
States
The life of a door
Four states, four events
| State | Door is | Parcel inside | Code works | In the free queue |
|---|---|---|---|---|
| FREE | shut | no | there is none | yes |
| LOADING | open | any moment now | there is none | no |
| HOLDING | shut | yes | until the end of the stay | no |
| EMPTYING | open | leaving | already used | no |
occupied: bool they look the same.This page uses an enum and a few ifs, because the two events touch two states each. When each state reacts to many events, the State pattern pays for itself. Four states alone are not a reason.
Design, first try
The design most people draw first
The design to avoid: people who act, doors with families, one class for the rest
1/4One class for everything
Choosing, codes, text messages, timers and cables in one Singleton. A new message provider and a new lock both change this file.
usesowns (dies together)extends (is a)
class LockerSystem: def store(self, parcel): for door in self.doors: if door.can_fit(parcel) and not door.occupied: # check door.occupied = True # act, a moment later door.code = str(random.randint(1000, 9999)) # guessable, and not unique send_sms(parcel.phone, door.code) # before the door was even opened door.timer = threading.Timer(3 * 86400, door.clear) door.timer.start() # one thread for each parcel return door def open(self, door, code): if door.code == code: door.occupied = False # free while a hand is inside return True return FalseFive bugs, each with a person in front of it
- 1
Two couriers, one door
Check and act are two steps, so two couriers get door 3. One opens it and finds a stranger's parcel.
- 2
A code for nothing
The message is sent before the parcel is inside. The courier's hand is too slow, the customer's is faster, and the door is empty.
- 3
Four digits from
randomNine thousand codes, made by a generator that is not meant for secrets, and nobody checks whether the code is in use.
- 4
The timer empties the door
clearsets the door free, and the parcel is still inside. Software cannot lift a parcel. - 5
Free too early
The door counts as free when the code is typed. The next courier may be sent to a door that is open.
Design, better
The design to reach
The design to reach: the locker orders steps, the rack owns free doors, the stay holds the code
1/6Three verbs and a sensor
A courier deposits. A customer picks up. A courier takes back what nobody came for. Between them, doors are shut, and the wire tells us: doorShut is an input like the others.
owns (dies together)useshas (lives on)
number = locker.deposit(parcel) # claims and unlocks a door, or Nonelocker.door_shut(number) # the sensor: makes the code, sends itlocker.pick_up("482913") # unlocks; the code is used uplocker.door_shut(number) # the sensor: the door is free againRoles
What each class owns
| Class | Knows | Does | Does not know |
|---|---|---|---|
Locker | Doors, living stays, one lock | Orders the steps of the three verbs | Which door is best, how locks are wired |
Rack | Free doors by size | Claims and takes back | Parcels, codes, time |
Door | Number, size, state, parcel | Nothing by itself | Codes and deadlines |
Stay | Parcel, door, code, end | Nothing: an unchanging record | Whether it is over: that depends on now |
Hardware | Relays and sensors | Unlocks | Why |
Notifier | A message service | Sends | What a locker is |
CodeMaker | A source of randomness | Makes a code | Whether it is in use |
Flow
From van to hand
Deposit
Pick up
Choosing
Which door?
The smallest free door that fits
Going up without limit is the simple rule, and it has a price: small parcels can eat all large doors. A measured comparison of three rules is on the page Which door.
Time
Two ends of a stay
The code ends by itself
- At pick up, compare the clock with the end of the stay
- No timer, no thread, nothing to lose in a restart
- Exactly at the end the code is refused:
now >= until
The door ends by itself
- A timer sets the door free after three days
- The parcel is still inside
- The next courier opens a full door
What is true after three days
How does the locker know that a parcel is overdue?
BreaksA timer for each parcel sets the door free
- How
- Start a timer at deposit. When it fires, clear the door.
- Limit
- The parcel is still there. Timers live in memory and die with the process. An extension must find and cancel the right one.
- Choose when
- Never for things that a person must move.
WorksA sweep every hour
- How
- A job walks over all stays and marks the late ones.
- Limit
- Between two sweeps a late code still works, unless pick up checks too. Then why mark?
- Choose when
- To send reminders and lists, which may be an hour late.
StrongCompare when somebody asks
- How
- The stay holds
until. Pick up compares, andoverdue()lists. Nothing happens on its own. - Limit
- Listing looks at all stays, which is nothing for one wall.
- Choose when
- The base design. Add a sweep for messages and an ordered list of ends for many sites.
Secret
Six digits, and how safe they are
Sixty doors hold parcels, so sixty codes out of a million open something. Somebody types at random. The keypad allows five wrong codes in any ten minutes, which is 720 tries a day.
| Digits | One try | One day, 720 tries | Meaning |
|---|---|---|---|
| 4 | 60 / 10,000 = 0.6% | more than 98% | A lucky afternoon without the limit, a certain day with it |
| 6 | 60 / 1,000,000 = 0.006% | about 4.2% | Of 24 such walls, about one is opened each day by a patient stranger |
| 8 | 0.00006% | about 0.043% | One day in 2,300 |
Summary
The whole topic in one minute.
A door is free, loading, holding or emptying. The code is made when the loaded door has been shut, belongs to the stay and works once, until its end. The door is free when it has been shut again.
Decide under one short lock, move metal and send messages outside it. The end of the code is a comparison, the end of the occupation needs a person. For real hardware write the intent first and compare with the sensors after a restart.
- Four states: free, loading, holding, emptying. Open is not the same as empty.
- The code is made when the door has been shut, and it belongs to the stay.
- The door is free when it has been shut again, not when the code was typed.
- The end of the code is a comparison. The end of the parcel needs a person.
- Claim under the lock, talk to metal and phones outside it.
Sources
- RFC 4226: HOTP, an HMAC-based one-time password algorithm
- RFC 6238: TOTP, time-based one-time passwords
- NIST SP 800-63B-4: authentication
- Python: secrets
- Redis: EXPIRE
- Amazon SQS: visibility timeout
- HashiCorp Vault: lease, renew and revoke
- Kubernetes: controllers
- SQLite: atomic commit
- Wikipedia: Parcel locker
- Wikipedia: Amazon Locker
- Wikipedia: InPost