AlgoViz

Design a parcel locker

medium 80 min

Model a wall of doors where couriers leave parcels and customers collect them with a code.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:48

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

  1. 2001

    Deutsche Post starts Packstation as a pilot in Dortmund and Mainz, on machines built by KEBA from Linz.

  2. 2005

    RFC 4226 describes one-time passwords from a counter (HOTP), with a throttling rule for short codes. Published in December.

  3. 2009

    The Integer.pl group introduces InPost lockers in Poland.

  4. 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.

  5. 2016

    Python 3.6 brings the secrets module, so that codes are not made with random.

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.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

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.

The bread doors at the old mill
Old Mill12345

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

AskIf the answer isThen
Which sizes? May a small parcel use a larger door?Three; yes, upwards onlySizes with an order, and a search that starts at the parcel's own size
How does the customer prove themselves?A code by text messageA Stay that can be found by its code
How long is the code valid?Three daysAn end on the stay, and a clock that is passed in
What happens after that?A courier takes the parcel backoverdue and take_back. The door is not free before that
Do we know when a door is open or shut?Yes, there is a sensordoor_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 nowA Notifier with one method; the rest is named and left out
The fifth question is the one most people miss. It decides whether a door has two states or four.

States

The life of a door

Four states, four events

Two arrows are drawn by people who type, two by a sensor. Every arrow is one short locked step in the code.
StateDoor isParcel insideCode worksIn the free queue
FREEshutnothere is noneyes
LOADINGopenany moment nowthere is noneno
HOLDINGshutyesuntil the end of the stayno
EMPTYINGopenleavingalready usedno
Read the last column: three different reasons for not being free. With 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

LockerSystem- instance: LockerSystem- doors: List<Door>- codes: Map<code, door>+ getInstance()+ isFull(size): bool+ store(parcel, courier)+ sendSms(phone, text)+ open(door, code): bool+ startTimer(door)

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)

Python
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 False
Before. It works in the demo. It sells one door twice, sends a code for an empty door, calls a full door empty after three days, and loses all timers when the power fails.

Five bugs, each with a person in front of it

  1. 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. 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. 3

    Four digits from random

    Nine thousand codes, made by a generator that is not meant for secrets, and nobody checks whether the code is in use.

  4. 4

    The timer empties the door

    clear sets the door free, and the parcel is still inside. Software cannot lift a parcel.

  5. 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

Locker- doors: Map<int, Door>- stays: Map<code, Stay>- lock: Lock+ deposit(parcel): int?+ pickUp(code): int+ doorShut(number)+ overdue(): List<Stay>+ takeBack(door): Parcel

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)

A question mark means that the answer may be nothing: no free door that fits is an ordinary result.
Python
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 again
After, seen from outside. The same event means two things, and the state of the door says which.

Roles

What each class owns

ClassKnowsDoesDoes not know
LockerDoors, living stays, one lockOrders the steps of the three verbsWhich door is best, how locks are wired
RackFree doors by sizeClaims and takes backParcels, codes, time
DoorNumber, size, state, parcelNothing by itselfCodes and deadlines
StayParcel, door, code, endNothing: an unchanging recordWhether it is over: that depends on now
HardwareRelays and sensorsUnlocksWhy
NotifierA message serviceSendsWhat a locker is
CodeMakerA source of randomnessMakes a codeWhether it is in use

Flow

From van to hand

Deposit

The last two arrows are the point. The message follows the sensor, not the wish of the courier.

Pick up

The code dies at the first step, the door is free at the last one.

Choosing

Which door?

The smallest free door that fits

Full is a property of a parcel, not of the wall. A wall with five small doors free is full for a cake.

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

The middle state is the one beginners leave out. It can last for days, and the wall is smaller while it does.

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, and overdue() 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.

DigitsOne tryOne day, 720 triesMeaning
460 / 10,000 = 0.6%more than 98%A lucky afternoon without the limit, a certain day with it
660 / 1,000,000 = 0.006%about 4.2%Of 24 such walls, about one is opened each day by a patient stranger
80.00006%about 0.043%One day in 2,300
Assumption: 60 valid codes and a limit for each keypad. The surprise is that the codes of all neighbours help the guesser. More digits, a limit, or asking for the phone's last digits as well.

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