Design Amazon Locker
📦 What is Amazon Locker? It is a wall of self-service lockers in a shop or a station. A courier puts your package into a free locker, and you get a short code by text or email. You walk up, type the code, and the right door pops open. If you never come, the package goes back after a few days.
This problem looks like the parking lot at first: things of different sizes go into slots of different sizes. The interesting parts are elsewhere. The customer proves who they are with nothing but a code, so the code has to be safe and must work exactly once. And packages that nobody collects must expire, which brings in time, a rule people often get wrong under pressure.
Requirements
"Design a package locker system like Amazon Locker. Couriers drop packages off, customers pick them up with a code."
The prompt is short on purpose. The questions below are the ones that decide the classes and the tests.
Clarifying Questions
You: What sizes are there, and which packages fit which lockers?
Interviewer: Small, medium and large, for both lockers and packages. A package fits a locker of its own size or bigger.
You: When several lockers fit, which one does the package get?
Interviewer: The smallest size that fits and is free. We don't want small boxes filling the large lockers.
You: How does the customer open the locker? Do they have an account at the station?
Interviewer: No account. When the package goes in, the system makes a pickup code and sends it to the customer. Whoever types the code gets the package. A code works once.
You: How long can a package wait?
Interviewer: A fixed hold time, the same for every package. Say three days in real life; make it a parameter.
You: What happens when the hold time runs out?
Interviewer: The code stops working. The package stays in the locker until a courier comes and takes all expired packages out, and then those lockers are free again.
You: Is this one station or the whole network of stations?
Interviewer: One station for now. We can talk about many later.
You: How do we know the time?
Interviewer: Pass a timestamp in minutes with every call.
The fifth answer is the one to slow down on. "Expired" and "free" are two different moments. Between them, an expired package still takes up its locker, so a new deposit cannot use it. Ask this explicitly: many candidates free the locker the instant the code expires, which is a different system.
💡 Interview tip: Whenever a problem has a deadline ("expires", "times out", "holds for N minutes"), ask two things: is the boundary minute included, and what physically happens at the deadline? The first decides a
<versus<=in your code. The second decides whether you need a cleanup step at all.
Final Requirements
- The station has a fixed number of small, medium and large lockers.
- A package fits a locker of its own size or larger. A deposit gets a locker of the smallest size that fits and is free. If nothing fits, the deposit is refused.
- A package that is already in a locker cannot be deposited again.
- Every successful deposit creates a pickup code. A code belongs to one package and works only once.
- Entering a valid code within the hold time opens the locker, frees it and returns the package.
- A package can be picked up until
deposit time + hold time(inclusive). After that the code no longer works, but the package keeps its locker. - A courier can remove all expired packages at once. Their lockers become free again.
- Anyone can ask how many lockers of a size are free (for the courier's handheld and for a website).
Out of scope
- Sending the code to the customer (text, email, app).
- Payments, refunds and the shop's order system.
- The physical doors, the touch screen and the camera.
- Several stations, reservations before delivery and returns (we come back to these in Extensibility).
Entities and Relationships
Underline the nouns in the requirements and keep the ones that hold state or enforce a rule.
- LockerStation: the whole wall of lockers and the entry point. Couriers and customers only ever talk to it.
- Locker: one door, with an id and a size.
- Assignment: the record that a package is sitting in a locker. It ties together the package id, the locker, the pickup code and the moment the code expires. It is the locker's version of the parking lot's ticket.
- CodeGenerator: the rule that makes new pickup codes. It is its own entity because "how codes are made" is a security decision, and because tests need a version that is not random.
Some nouns do not need a class:
- Package is just an id and a size. It has no behavior here, so the assignment stores the id and the deposit call passes the size.
- PickupCode is a string. Wrapping it in a class adds nothing until codes get rules of their own (like a limit on wrong tries).
- Size is an enum:
SMALL,MEDIUM,LARGE. - Courier and Customer are callers of the station, not parts of it.
Who owns whom:
| Owner | Owns | How many |
|---|---|---|
| LockerStation | Locker | all lockers, free or busy |
| LockerStation | Assignment | one per package in a locker |
| Assignment | Locker (reference) | exactly one |
| LockerStation | CodeGenerator | exactly one, swappable |
A Locker does not point back to its assignment, and it has no occupied flag. A locker is free exactly when it is in the station's free list. Keeping that fact in one place means the two can never disagree.
Class Design
We go top down, from the class the outside world calls. The station checks the request, asks its parts for a locker and a code, and records the result.
LockerStation
The orchestrator. It answers the four requests: deposit, pickup, remove expired, and count free lockers.
class LockerStation:
hold_time: int # requirement 6
codes: CodeGenerator # requirement 4: injected
free: Dict[Size, List[Locker]] # requirements 2 and 8
by_code: Dict[str, Assignment] # code -> package still in a locker
packages_inside: Set[str] # requirement 3
expiry_queue: Deque[Assignment] # requirement 7, see Implementation
def __init__(self, lockers: List[int], hold_time: int,
codes: Optional[CodeGenerator] = None): ...
def deposit(self, package_id: str, size: str, timestamp: int) -> str: ... # code or ""
def pickup(self, code: str, timestamp: int) -> str: ... # package id or ""
def remove_expired(self, timestamp: int) -> List[str]: ...
def free_lockers(self, size: str) -> int: ...
by_code is keyed by the code because that is the only thing a customer brings to the screen. packages_inside is a separate set so the duplicate check is one lookup. The expiry queue looks odd now; it is the answer to "how do we find expired packages quickly", which we work out below.
Locker
@dataclass
class Locker:
locker_id: int
size: Size
A small value object. The id is what the hardware needs to open the right door.
Assignment
@dataclass
class Assignment:
code: str
package_id: str
locker: Locker # which door to open, and which free list to return it to
expires_at: int # deposit time + hold time: the last minute the code works
We store expires_at instead of the deposit time. Every check we make later ("can this code still be used?", "has this package expired?") compares against the deadline, so computing it once at deposit keeps those checks short and in one form.
CodeGenerator
class CodeGenerator:
def next_code(self) -> str: ...
class RandomCodeGenerator(CodeGenerator): ... # production: secure random six digits
class SequenceCodeGenerator(CodeGenerator): ... # tests: a fixed, repeatable sequence
A one-method interface with two implementations, and both are needed today: one for real lockers and one for tests. That is the clearest sign an interface earns its place.
class Size(Enum):
SMALL = "SMALL"
MEDIUM = "MEDIUM"
LARGE = "LARGE"
SIZES: List[Size] = [Size.SMALL, Size.MEDIUM, Size.LARGE] # smallest first
Implementation
We follow a package through its life: it is deposited, then either picked up or left until it expires and is removed.
Depositing a package
def deposit(self, package_id: str, size: str, timestamp: int) -> str:
if package_id in self.packages_inside: # requirement 3
return ""
locker = self._find_locker(Size(size)) # requirement 2
if locker is None:
return ""
code = self.codes.next_code() # requirement 4
while code in self.by_code: # a random code could repeat a live one
code = self.codes.next_code()
assignment = Assignment(code, package_id, locker, timestamp + self.hold_time)
self.by_code[code] = assignment
self.packages_inside.add(package_id)
self.expiry_queue.append(assignment)
return code
The code is made only after a locker was found, so a refused deposit never uses a code. The while loop matters for random codes: two packages that are waiting at the same time must never share a code, or the second customer could open the first customer's locker.
Picking the locker is the same problem as picking a parking spot, so we keep it short. A first draft that walks all lockers and takes the first free one that fits has a real bug, not just a speed problem: if large lockers happen to come first in the list, small packages fill them. Keeping one free list per size and trying sizes from smallest to largest fixes both the rule and the speed.
def _find_locker(self, size: Size) -> Optional[Locker]:
# The package fits its own size or any bigger one; try the smallest first.
for candidate in SIZES[SIZES.index(size):]:
if self.free[candidate]:
return self.free[candidate].pop()
return None
SIZES[SIZES.index(size):] is "this size and everything bigger, smallest first", so the fit rule and the search order are the same line. Taking and returning a locker are a pop and an append. See /low-level-design/parking-lot for the longer comparison of scanning versus free lists.
Making pickup codes
The code is the only thing standing between a stranger and someone else's package. How we make it is the main design choice in this problem.
Bad Solution: the locker number or a counter
Approach
Use something we already have: the locker id, or a counter that goes 1001, 1002, 1003....
def deposit(self, package_id: str, size: str, timestamp: int) -> str:
...
self.counter += 1
code = str(self.counter)
...
Challenges
It is unique and easy, and it is completely unsafe. If my code is 1042, I can guess that 1041 and 1043 belong to other people who are waiting right now. Locker ids are even worse: there are only a few dozen of them, and printed on the doors. A code that can be guessed is not a code. Interviewers bring this up on purpose to see whether you think about the person who is not supposed to open the door.
Good Solution: random codes inside the station
Approach
Draw six random digits with a secure random source, and draw again if the code is already in use.
import secrets
def _new_code(self) -> str:
while True:
code = "%06d" % secrets.randbelow(1_000_000)
if code not in self.by_code:
return code
Challenges
This is safe enough: with a few hundred packages waiting among a million possible codes, a random guess almost never hits a live one. (Use secrets, not random. The random module is predictable if someone sees enough of its output.) The problem is testing. Every run gives different codes, so a test cannot say "the second deposit returns this code", and every test must first read the code back before it can pick up. The rule is also buried in the station, so changing it (eight characters, letters and digits) means editing the class that also handles lockers and expiry.
Great Solution: an injected code generator
Approach
Move code making behind a one-method interface and pass it to the station. Production passes the random generator; tests pass a fixed sequence. The station keeps the one rule that belongs to it: a new code must not match a live one.
class CodeGenerator:
def next_code(self) -> str:
raise NotImplementedError
class RandomCodeGenerator(CodeGenerator):
def next_code(self) -> str:
return "%06d" % secrets.randbelow(1_000_000)
class SequenceCodeGenerator(CodeGenerator):
"""The k-th code is (k * 7919) mod 1,000,000, as six digits: repeatable, and no repeats."""
def __init__(self):
self.count = 0
def next_code(self) -> str:
self.count += 1
return "%06d" % (self.count * 7919 % 1_000_000)
station = LockerStation([10, 6, 4], hold_time=3 * 24 * 60, codes=RandomCodeGenerator())
Challenges
One more small class, and it pays for itself immediately. The tests can now say exactly which code each deposit gets, and the practice tests use the sequence generator (7919 is a prime, so the first million codes are all different). The station's job stays "codes are unique among waiting packages", and the generator's job is "codes are hard to guess". Each can change without the other. This is the Strategy pattern used for testability: see /low-level-design/strategy-pattern.
⚠️ Common mistake: Reading the system clock or
randomdeep inside a class. It makes the class impossible to test with exact expectations. Pass time in as an argument and pass randomness in as an object. Both choices also make your walkthrough at the end of the interview much easier.
Picking up
def pickup(self, code: str, timestamp: int) -> str:
assignment = self.by_code.get(code)
if assignment is None or timestamp > assignment.expires_at:
return "" # unknown or used code, or the hold time is over
self._release(assignment)
return assignment.package_id
def _release(self, assignment: Assignment) -> None:
del self.by_code[assignment.code]
self.packages_inside.discard(assignment.package_id)
self.free[assignment.locker.size].append(assignment.locker)
_release removes the code from by_code, which is what makes a code work only once: the second try finds nothing. It also puts the locker back on its size's free list and lets the package id be deposited again later.
Notice what an expired pickup does: nothing. It returns "" and leaves the assignment in place, because requirement 6 says the package keeps its locker until a courier removes it. The comparison is timestamp > expires_at, so the last minute of the hold time still works.
An assignment moves through a small set of states. We do not store the state as a field; it follows from where the assignment is and what time it is.
Removing expired packages
The courier presses "collect expired" on a handheld. We need every package whose deadline has passed, in a stable order.
Bad Solution: a timer per package
Approach
When a package goes in, start a timer that fires at its deadline and frees the locker.
import threading
def deposit(self, package_id: str, size: str, timestamp: int) -> str:
...
timer = threading.Timer(self.hold_time * 60, self._expire, args=[assignment])
timer.start()
return code
Challenges
This frees the locker at the deadline, but the package is still physically inside it, so the next courier would be sent to a full locker. That breaks requirement 6 and 7 outright. It also brings threads into a problem that did not need any: the timer fires on another thread while a pickup may be running, so now we need locks. And it reads the real clock, so tests would have to wait three days.
Good Solution: scan all waiting packages
Approach
Do nothing at the deadline. Check the deadline in pickup (we already do), and when the courier asks, walk all waiting packages.
def remove_expired(self, timestamp: int) -> List[str]:
expired = [a for a in self.by_code.values() if a.expires_at < timestamp]
expired.sort(key=lambda a: a.expires_at)
for assignment in expired:
self._release(assignment)
return [a.package_id for a in expired]
Challenges
This is correct and simple, and for one station with a hundred lockers it is fast enough. Doing nothing until someone asks is called lazy expiry, and it is the right instinct. The cost is that every sweep walks every waiting package, even if only one expired, plus a sort. The sort is also fragile: two packages with the same deadline come out in whatever order the dictionary gives, so we would need a second sort key to make the order stable.
Great Solution: a queue in deposit order
Approach
Every package gets the same hold time, and timestamps never go backwards. So the order in which packages are deposited is exactly the order in which they expire. A plain first-in, first-out queue is already sorted by deadline. The sweep pops from the front while the front has expired and stops at the first one that has not.
def remove_expired(self, timestamp: int) -> List[str]:
removed: List[str] = []
while self.expiry_queue and self.expiry_queue[0].expires_at < timestamp:
assignment = self.expiry_queue.popleft()
if self.by_code.get(assignment.code) is assignment: # skip packages already picked up
self._release(assignment)
removed.append(assignment.package_id)
return removed
Challenges
A picked-up package is still in the queue, because removing it from the middle of a queue is slow. Instead we leave it there and skip it when the sweep reaches it: this is lazy deletion. The check self.by_code.get(assignment.code) is assignment asks "is this exact assignment still waiting?". We compare the object, not just the code, because with random codes a later package could have been given the same code after the first one was collected.
Each assignment enters the queue once and leaves once, so a sweep costs only the number of entries it pops, and the result comes out in deposit order for free. The trade-off to say out loud: this only works because the hold time is the same for everyone. If hold times differ (one day for groceries, five days for everything else), deposit order is no longer deadline order, and the queue becomes a min-heap keyed on (expires_at, deposit number). The rest of the station does not change.
💡 Interview tip: Before you reach for a heap, ask whether the data already arrives in the order you need. A queue beats a heap whenever every item gets the same delay, which is common: hold times, retry backoffs with one fixed delay, cache entries with one time-to-live.
Edge cases
Walk through these before you say you are done:
- No locker fits:
_find_lockerreturnsNone,depositreturns"", and no code is used. - Same package twice:
packages_insiderefuses it before a locker is taken. - Code used twice: the first pickup deletes it from
by_code, so the second finds nothing. - Pickup at the last minute:
timestamp == expires_atpasses, because the check is>. - Pickup after the deadline: refused, and the package keeps its locker. A deposit cannot use that locker until the sweep.
- Sweep at the deadline minute:
expires_at < timestampis false, so a package that can still be picked up is never removed. - Zero hold time: the code works only in the minute of the deposit. Nothing special is needed.
- Package id reused: after a pickup or a sweep the id leaves
packages_inside, so the same id can come back and gets a new code.
Verification
Let's trace a station with one locker of each size and a hold time of 100 minutes. This is the first practice test.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | deposit("P1", "SMALL", 0) |
Small locker; 1st code; expires at 100 | "007919" |
| 2 | deposit("P2", "SMALL", 5) |
Small is full; next size is medium | "015838" |
| 3 | deposit("P3", "LARGE", 10) |
Large locker; expires at 110 | "023757" |
| 4 | deposit("P4", "MEDIUM", 20) |
Medium and large are both taken; no code used | "" |
| 5 | free_lockers("LARGE") |
The only large locker holds P3 | 0 |
| 6 | pickup("015838", 50) |
P2 is waiting and 50 ≤ 105; medium locker freed | "P2" |
| 7 | deposit("P4", "MEDIUM", 60) |
Medium is free again; 4th code | "031676" |
| 8 | pickup("015838", 61) |
That code was deleted in step 6 | "" |
| 9 | pickup("007919", 101) |
P1 expired at 100; it stays in its locker | "" |
| 10 | remove_expired(120) |
Queue: P1 (100) removed, P2 skipped (picked up), P3 (110) removed, P4 (160) stops the sweep | ["P1", "P3"] |
| 11 | free_lockers("SMALL") |
Step 10 freed P1's locker | 1 |
Step 10 shows lazy deletion at work: P2's entry was still in the queue, and the sweep skipped it without any special code in pickup.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from collections import deque
from dataclasses import dataclass
from enum import Enum
from typing import Deque, Dict, List, Optional, Set
class Size(Enum):
SMALL = "SMALL"
MEDIUM = "MEDIUM"
LARGE = "LARGE"
SIZES: List[Size] = [Size.SMALL, Size.MEDIUM, Size.LARGE] # smallest first
@dataclass
class Locker:
locker_id: int
size: Size
@dataclass
class Assignment:
"""One package sitting in one locker, waiting for its code."""
code: str
package_id: str
locker: Locker
expires_at: int # last minute the code still works
class CodeGenerator:
def next_code(self) -> str:
raise NotImplementedError
class SequenceCodeGenerator(CodeGenerator):
"""Deterministic codes for tests: the k-th code is (k * 7919) mod 1,000,000, as six digits."""
def __init__(self):
self.count = 0
def next_code(self) -> str:
self.count += 1
return "%06d" % (self.count * 7919 % 1000000)
class LockerStation:
def __init__(self, lockers: List[int], hold_time: int, codes: Optional[CodeGenerator] = None):
self.hold_time = hold_time
self.codes = codes or SequenceCodeGenerator()
self.free: Dict[Size, List[Locker]] = {size: [] for size in SIZES}
next_id = 0
for size, count in zip(SIZES, lockers): # counts are [small, medium, large]
for _ in range(count):
self.free[size].append(Locker(next_id, size))
next_id += 1
self.by_code: Dict[str, Assignment] = {} # code -> package still in a locker
self.packages_inside: Set[str] = set()
self.expiry_queue: Deque[Assignment] = deque() # deposit order = expiry order
def deposit(self, package_id: str, size: str, timestamp: int) -> str:
if package_id in self.packages_inside:
return ""
locker = self._find_locker(Size(size))
if locker is None:
return ""
code = self.codes.next_code()
while code in self.by_code: # a random generator could repeat a live code
code = self.codes.next_code()
assignment = Assignment(code, package_id, locker, timestamp + self.hold_time)
self.by_code[code] = assignment
self.packages_inside.add(package_id)
self.expiry_queue.append(assignment)
return code
def pickup(self, code: str, timestamp: int) -> str:
assignment = self.by_code.get(code)
if assignment is None or timestamp > assignment.expires_at:
return "" # unknown or used code, or the hold time is over
self._release(assignment)
return assignment.package_id
def remove_expired(self, timestamp: int) -> List[str]:
removed: List[str] = []
while self.expiry_queue and self.expiry_queue[0].expires_at < timestamp:
assignment = self.expiry_queue.popleft()
if self.by_code.get(assignment.code) is assignment: # skip packages already picked up
self._release(assignment)
removed.append(assignment.package_id)
return removed
def free_lockers(self, size: str) -> int:
return len(self.free[Size(size)])
def _find_locker(self, size: Size) -> Optional[Locker]:
# The package fits its own size or any bigger one; try the smallest first.
for candidate in SIZES[SIZES.index(size):]:
if self.free[candidate]:
return self.free[candidate].pop()
return None
def _release(self, assignment: Assignment) -> None:
del self.by_code[assignment.code]
self.packages_inside.discard(assignment.package_id)
self.free[assignment.locker.size].append(assignment.locker)
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
These are the follow-ups interviewers ask most once one station works. For each, name the classes that change and the ones that stay put.
1) How would you support many stations and pick one for each order?
A customer chooses a station at checkout, or the system suggests the nearest one with space. That is a new class above the station, not a change inside it.
class LockerNetwork:
def __init__(self, stations: Dict[str, LockerStation], locations: Dict[str, Tuple[float, float]]):
self.stations = stations
self.locations = locations
def suggest(self, customer: Tuple[float, float], size: str) -> Optional[str]:
"""The closest station that has a free locker this package fits."""
fits = [sid for sid, st in self.stations.items() if st.can_fit(size)]
return min(fits, key=lambda sid: distance(customer, self.locations[sid]), default=None)
LockerStation gains one read-only helper, can_fit(size), which reuses the same "this size or bigger" rule as _find_locker without popping anything. How to rank stations (distance, travel time, opening hours) is a policy that will change, so if the interviewer pushes on it, it becomes a StationRanker strategy. In a real network the stations are separate machines and the network is a service in front of them, which is a system design question rather than a class design one.
2) How would you make sure a locker is free when the courier arrives?
Today a courier can drive to a station and find it full. The fix is to reserve a locker when the order ships, days before the package arrives. A reservation is a new kind of assignment that holds a locker but has no package and no code yet.
@dataclass
class Reservation:
reservation_id: str
locker: Locker
expires_at: int # if the courier never comes, give the locker back
def reserve(self, size: str, timestamp: int) -> str: ... # "" when nothing fits
def deposit_reserved(self, reservation_id: str, package_id: str, timestamp: int) -> str: ... # code
reserve takes a locker from the free list exactly like deposit. deposit_reserved turns the reservation into a normal Assignment with a code. A reservation that is never used expires too, so it goes into its own expiry queue (or the same min-heap, if its delay differs). pickup and the sweep for packages do not change. This is also why we kept Assignment separate from Locker: a locker can now be busy for two different reasons.
3) How would you handle returns?
For a return, the flow runs backwards: the customer drops a package off and a courier collects it. The station stays the same; what changes is who gets the code.
def start_return(self, package_id: str, size: str, timestamp: int) -> str:
"""The customer's drop-off code: opens an empty locker that fits."""
...
def drop_off(self, code: str, timestamp: int) -> bool:
"""The customer puts the package in; the courier gets a new pickup code."""
...
start_return reserves a locker (follow-up 2) and gives the customer a code that opens it empty. drop_off turns that into a normal assignment whose code goes to the courier instead of the customer. Who should be told about each code is exactly what the Observer pattern handles well: the station publishes "package deposited" and "package returned" events, and separate notifier classes send texts or update the shop's order status. See /low-level-design/observer-pattern.
4) What if a courier and a customer use the station at the same time?
The touch screen, the courier's handheld and a phone app can all call the station at once. Two deposits could pop the same last locker, or a pickup and the sweep could both release the same assignment, putting one locker on the free list twice. Each is a check-then-act race: one thread checks, another changes the state, then the first acts on stale information.
import threading
class LockerStation:
def __init__(self, lockers: List[int], hold_time: int, codes: Optional[CodeGenerator] = None):
...
self._lock = threading.Lock()
def deposit(self, package_id: str, size: str, timestamp: int) -> str:
with self._lock:
return self._deposit(package_id, size, timestamp) # the code from above
def pickup(self, code: str, timestamp: int) -> str:
with self._lock:
return self._pickup(code, timestamp)
One lock per station is the right answer here. Every call is a few dictionary operations, and a station serves a handful of people at a time, so nobody ever waits long. Finer locks (one per size) would not even be correct on their own, because a small package may need a medium locker, and the code map and the expiry queue are shared by all sizes. See /low-level-design/race-conditions-and-locks.
What is Expected at Each Level?
Junior
A junior candidate should model the station, the lockers and the record of a package in a locker, and get deposit and pickup working with the fit rule. A code that is simply a counter is acceptable at first, as long as they agree it is unsafe once the interviewer asks who else could type it. They should handle the obvious errors (no locker fits, a wrong code) and be able to trace a short example.
Mid-level
A mid-level candidate asks about sizes, the tie-breaking rule, the hold time and what happens at expiry without being prompted. They make codes random and unique among waiting packages, check the deadline at pickup, and keep expired packages in their lockers until the sweep. Their classes have clear jobs, time is passed in, and they can explain the cost of each method and the edge cases around the deadline minute.
Senior
A senior candidate does all of that quickly and spends the saved time on the reasons. They inject the code generator and say why (security in production, exact tests), notice that a fixed hold time makes deposit order equal to expiry order and use a queue with lazy deletion, and know when it must become a heap. On follow-ups they add reservations and returns as new kinds of assignment rather than flags on Locker, put many stations behind a separate network class, and protect one station with one lock and a clear reason why finer locks do not help.