LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 24 OF 42

Design an Amazon Locker System: LLD with Java Code

The parcel locker machine coding question, solved end to end: lockers, slots and parcels, best-fit slot choice as a strategy, claiming a slot with compare-and-set so two couriers never share one, one-time pickup codes, expiry and returns, notifications, and a full Java 17 solution with a 10-courier race.

Reported atAmazon

Patterns usedStrategy

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 16

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 219 lines, with a small main() demo. Save it as LockerSystem.java, then run javac LockerSystem.java && java LockerSystem.

import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;

/** Package lockers: best-fit slot assignment, one-time pickup codes, expiry and returns, no double use. */
public class LockerSystem {

    // ---------- the model ----------
    enum Size { SMALL, MEDIUM, LARGE }

    record Parcel(String id, String customer, Size size) {}

    /** What a slot holds: the parcel, its pickup code and when it must be collected by. */
    record Deposit(Parcel parcel, String code, Instant expires) {}

    static final class Slot {
        final String id;
        final Size size;
        private final AtomicReference<Deposit> held = new AtomicReference<>();

        Slot(String id, Size size) {
            this.id = id;
            this.size = size;
        }

        boolean fits(Parcel p) { return size.compareTo(p.size()) >= 0; }

        boolean tryFill(Deposit d) { return held.compareAndSet(null, d); }

        /** Empties the slot only if it still holds exactly this deposit. */
        boolean tryEmpty(Deposit d) { return held.compareAndSet(d, null); }

        Deposit deposit() { return held.get(); }
    }

    record Locker(String id, String pincode, List<Slot> slots) {}

    static final class LockerException extends RuntimeException {
        private static final long serialVersionUID = 1L;

        LockerException(String msg) { super(msg); }
    }

    // ---------- strategies and notifications ----------
    interface SlotStrategy { List<Slot> candidates(List<Locker> lockers, Parcel p, String pincode); }

    /** Lockers in the customer's pincode, smallest slot that fits first, so big slots stay free. */
    static final class BestFit implements SlotStrategy {
        @Override
        public List<Slot> candidates(List<Locker> lockers, Parcel p, String pincode) {
            List<Slot> out = new ArrayList<>();
            for (Locker l : lockers) {
                if (!l.pincode().equals(pincode)) continue;
                for (Slot s : l.slots()) if (s.fits(p) && s.deposit() == null) out.add(s);
            }
            out.sort(Comparator.comparing((Slot s) -> s.size));
            return out;
        }
    }

    interface Notifier { void send(String customer, String message); }

    // ---------- the service ----------
    private final List<Locker> lockers = new ArrayList<>();
    private final Map<String, Slot> slotByCode = new ConcurrentHashMap<>();
    private final SlotStrategy strategy;
    private final Notifier notifier;
    private final Supplier<Instant> clock;
    private final Duration keepFor;
    private final SecureRandom random = new SecureRandom();

    LockerSystem(SlotStrategy strategy, Notifier notifier, Supplier<Instant> clock, Duration keepFor) {
        this.strategy = strategy;
        this.notifier = notifier;
        this.clock = clock;
        this.keepFor = keepFor;
    }

    void addLocker(Locker l) { lockers.add(l); }

    /** The courier drops a parcel: claim the best free slot atomically and text the customer a code. */
    Optional<String> deposit(Parcel p, String pincode) {
        for (Slot s : strategy.candidates(lockers, p, pincode)) {
            String code = reserveCode(s);              // unique: reserved with putIfAbsent
            Deposit d = new Deposit(p, code, clock.get().plus(keepFor));
            if (!s.tryFill(d)) {                        // another courier took this slot a moment ago
                slotByCode.remove(code, s);
                continue;
            }
            notifier.send(p.customer(), "Parcel " + p.id() + " is in slot " + s.id + ", code " + code);
            return Optional.of(s.id);
        }
        return Optional.empty();                      // no slot: send the parcel to the nearest depot
    }

    /** The customer types the code: it works exactly once and only before expiry. */
    Parcel pickUp(String code) {
        Slot s = slotByCode.remove(code);               // remove first: a code can never be used twice
        if (s == null) throw new LockerException("wrong or used code");
        Deposit d = s.deposit();
        if (d == null || !d.code().equals(code)) throw new LockerException("wrong or used code");
        if (clock.get().isAfter(d.expires())) {
            slotByCode.put(code, s);                  // leave it for the return sweep
            throw new LockerException("code expired, parcel is being returned");
        }
        if (!s.tryEmpty(d)) throw new LockerException("slot changed");
        return d.parcel();
    }

    /** Daily sweep: expired parcels are taken out by the courier and sent back. */
    List<Parcel> collectExpired() {
        List<Parcel> back = new ArrayList<>();
        Instant now = clock.get();
        for (Locker l : lockers) {
            for (Slot s : l.slots()) {
                Deposit d = s.deposit();
                if (d == null || !now.isAfter(d.expires())) continue;
                if (s.tryEmpty(d)) {
                    slotByCode.remove(d.code());
                    back.add(d.parcel());
                    notifier.send(d.parcel().customer(), "Parcel " + d.parcel().id() + " returned to sender");
                }
            }
        }
        return back;
    }

    long free(Size size) {
        long n = 0;
        for (Locker l : lockers) for (Slot s : l.slots()) if (s.size == size && s.deposit() == null) n++;
        return n;
    }

    private String reserveCode(Slot s) {
        while (true) {
            String code = String.format("%06d", random.nextInt(1_000_000));
            if (slotByCode.putIfAbsent(code, s) == null) return code;
        }
    }

    // ---------- demo ----------
    static Locker locker(String id, String pincode, int small, int medium, int large) {
        List<Slot> slots = new ArrayList<>();
        for (int i = 1; i <= small; i++) slots.add(new Slot(id + "-S" + i, Size.SMALL));
        for (int i = 1; i <= medium; i++) slots.add(new Slot(id + "-M" + i, Size.MEDIUM));
        for (int i = 1; i <= large; i++) slots.add(new Slot(id + "-L" + i, Size.LARGE));
        return new Locker(id, pincode, List.copyOf(slots));
    }

    public static void main(String[] args) throws InterruptedException {
        Instant[] now = { Instant.parse("2026-11-20T10:00:00Z") };
        Map<String, String> lastText = new ConcurrentHashMap<>();
        LockerSystem sys = new LockerSystem(new BestFit(), (c, msg) -> lastText.put(c, msg),
                () -> now[0], Duration.ofDays(3));
        sys.addLocker(locker("BLR1", "560001", 1, 2, 1));
        sys.addLocker(locker("DEL1", "110001", 2, 2, 2));

        String slot = sys.deposit(new Parcel("P1", "asha", Size.SMALL), "560001").orElseThrow();
        String code = lastText.get("asha").replaceAll(".*code ", "");
        System.out.println("P1 (small) -> " + slot);
        System.out.println("P2 (small) -> " + sys.deposit(new Parcel("P2", "ravi", Size.SMALL), "560001")
                .orElseThrow() + " (no small left, next size up)");
        System.out.println("P3 (large) -> " + sys.deposit(new Parcel("P3", "meera", Size.LARGE), "560001")
                .orElseThrow());
        System.out.println("P4 (large) -> " + sys.deposit(new Parcel("P4", "dev", Size.LARGE), "560001")
                .orElse("no slot, send to depot"));

        System.out.println("asha picks up with her code: " + sys.pickUp(code).id());
        try {
            sys.pickUp(code);
        } catch (LockerException e) {
            System.out.println("same code again: " + e.getMessage());
        }

        now[0] = now[0].plus(Duration.ofDays(4));
        String ravi = lastText.get("ravi").replaceAll(".*code ", "");
        try {
            sys.pickUp(ravi);
        } catch (LockerException e) {
            System.out.println("ravi after 4 days: " + e.getMessage());
        }
        System.out.println("sweep returned: " + sys.collectExpired().stream().map(Parcel::id).toList());

        // Race: 10 couriers drop medium parcels into Delhi at once; 2 medium + 2 large slots exist.
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch go = new CountDownLatch(1);
        AtomicInteger placed = new AtomicInteger();
        Map<String, String> bySlot = new ConcurrentHashMap<>();
        for (int i = 0; i < 10; i++) {
            Parcel p = new Parcel("R" + i, "c" + i, Size.MEDIUM);
            pool.submit(() -> {
                go.await();
                sys.deposit(p, "110001").ifPresent(s -> {
                    placed.incrementAndGet();
                    if (bySlot.putIfAbsent(s, p.id()) != null) throw new AssertionError("slot shared");
                });
                return null;
            });
        }
        go.countDown();
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Race: 10 medium parcels, 4 slots that fit, placed " + placed.get());
        if (placed.get() != 4) throw new AssertionError("expected 4");
    }
}

Notes

Requirements

Fix the scope. Lockers sit in many locations, each with small, medium and large slots. A courier drops a parcel into the smallest free slot that fits in the customer's area. The customer gets a six digit code that opens that slot exactly once. If they do not collect it within three days, the parcel goes back to the sender. Many couriers work at once. Payment and the door hardware are out of scope.

Requirements
  • lockers in many locations
  • slots: small, medium, large
  • courier drops a parcel in the
  • smallest slot that fits
  • customer gets a 6-digit code
  • code opens the slot once
  • collect within 3 days, else the
  • parcel goes back to the sender
  • many couriers at once
  • out of scope: payments, hardware

Entities

Underline the nouns: locker, slot, parcel, code. A locker has an id, a pincode and a list of slots. A slot has a size and holds at most one deposit. The deposit is the key idea: a small immutable record bundling the parcel, its pickup code and its expiry time. Because the three always change together, keeping them in one record means a slot is either fully empty or fully filled, never half.

The model
enum Size { SMALL, MEDIUM, LARGE }
record Parcel(String id,
              String customer, Size s)
record Deposit(Parcel parcel,
               String code, Instant exp)
class Slot: id, size,
  AtomicReference<Deposit> held
record Locker(String id,
              String pincode, List<Slot>)

Class diagram

Where does the rule live that a large box cannot go in a small slot? On the slot, because the slot owns its size. Declare the sizes in order from small to large and the rule becomes one comparison: a slot fits a parcel if its size is at least the parcel's size. Adding an extra large size later is one new enum value, and the rule still works.

Slot.fits()
boolean fits(Parcel p) {
  return size.compareTo(p.size()) >= 0;
}

enum order is SMALL < MEDIUM < LARGE
small parcel: any slot
medium parcel: medium or large
large parcel: large only

Strategy: slot choice

Which slot to use is a policy, so it sits behind a strategy. Our default is best fit: look at lockers in the customer's pincode, keep free slots that fit, and sort smallest first. A small parcel takes a small slot if one is free, and only spills into a medium one when all small slots are full, so large slots stay free for large parcels. A nearest-to-home or wear-levelling policy would be a new class.

SlotStrategy
interface SlotStrategy {
  List<Slot> candidates(List<Locker> l,
                Parcel p, String pin);
}
BestFit: lockers in the pincode,
  free slots that fit,
  smallest size first
later: nearest to the customer,
  spread wear across lockers

Flow: deposit

The deposit flow. Ask the strategy for candidate slots in order. For each one, reserve a fresh pickup code, build the deposit with an expiry three days out, and try to fill the slot. If another courier filled it a moment earlier, release the code and try the next slot. On success, text the customer their code and tell the courier which door to open. If nothing fits, return empty so the courier takes the parcel to a depot.

deposit(parcel, pincode)
for (Slot s : strategy.candidates(..)) {
  String code = reserveCode(s);
  Deposit d = new Deposit(p, code,
                  now + 3 days);
  if (!s.tryFill(d)) {
    codes.remove(code, s); continue;
  }
  notifier.send(customer, code);
  return Optional.of(s.id);
}
return Optional.empty(); // depot

Concurrency

Two couriers at the same locker both see slot M1 free. If filling were check then set, both would put a parcel in one slot. Instead the slot holds an atomic reference and filling is compare-and-set from empty to this deposit. Exactly one wins and the other moves on. Emptying is compare-and-set from this exact deposit to empty, so a slow pickup can never clear a newer parcel that has since been put in the same slot.

No slot used twice
AtomicReference<Deposit> held

boolean tryFill(Deposit d) {
  return held.compareAndSet(null, d);
}
boolean tryEmpty(Deposit d) {
  return held.compareAndSet(d, null);
}

tryEmpty only clears THIS deposit

Flow: pickup

The pickup flow. The first step is to remove the code from the code index. Removal is atomic, so if someone types the same code twice, or two people race with it, only one removal finds the slot and the other gets wrong or used code. Then check the expiry, empty the slot with compare-and-set and open the door. One atomic remove is what makes the code one-time.

pickUp(code)
Slot s = codes.remove(code);
if (s == null) throw: wrong or used
Deposit d = s.deposit();
if (now > d.expires()) {
  codes.put(code, s); // for sweep
  throw: expired, being returned
}
s.tryEmpty(d);
return d.parcel();  // open the door

Security

The pickup code is a secret, so treat it like a password. Generate it with a secure random source, not the ordinary random class. Reserve it with put-if-absent so no two live parcels share a code. It works once and dies with the deposit. A keypad should lock after a few wrong tries in a row, since six digits is only a million guesses, and a real system stores a hash of the code rather than the code itself.

Code rules
  • SecureRandom, not Random
  • unique among live codes:
  • reserve with putIfAbsent
  • one use, then gone
  • expires with the deposit
  • lock the keypad after 5 wrong
  • tries in a row
  • never log the code
  • real system: store a hash

Expiry

Uncollected parcels need to go back. A sweep runs once a day, finds deposits past their expiry, empties those slots with the same compare-and-set, removes their codes and produces the list of parcels the courier should collect. The customer is told their parcel is being returned. The pickup flow also refuses expired codes, so a customer cannot open a slot the courier is about to empty.

collectExpired()
for each slot with a deposit:
  if (now <= d.expires()) continue;
  if (s.tryEmpty(d)) {
    codes.remove(d.code());
    back.add(d.parcel());
    notify: returned to sender
  }
return back;  // the courier's list

Notifications

Notifications sit behind a tiny interface. The locker system decides what to say: your parcel is in slot M1 with this code, a reminder on day two, your parcel has been returned. The notifier decides how: SMS, an app push, or email. Each channel is an implementation, so adding WhatsApp never touches the locker logic, and tests just record the messages.

Notifier
interface Notifier {
  void send(String customer,
            String message);
}
events: deposited (with code),
  reminder on day 2, returned
SMS, app push and email are
  just implementations

Concurrency

Check every shared field. Slot contents are an atomic reference, filled and emptied only with compare-and-set. The code index is a concurrent hash map: put-if-absent to reserve a code and remove to use it. Deposits and parcels are immutable records. The list of lockers is built at start-up and only read afterwards, and notifications are sent without holding anything.

Thread safety checklist
  • slot contents: AtomicReference
  • fill and empty with CAS
  • codes: ConcurrentHashMap
  • reserve: putIfAbsent
  • use: remove (one-time)
  • deposit, parcel: immutable
  • locker list: built at start
  • notifications: outside any lock

Extensibility

Now the follow-ups. Let the customer choose a locker at checkout? Reserve a slot ahead with an expiry, like a booking hold. Customer returns? A deposit whose code is sent to the courier instead. A broken door? An out-of-order flag the strategy skips. Chilled slots for groceries? A new slot feature and a strategy rule. With thousands of lockers, keep a free-slot index per locker and size instead of scanning.

Extension points
  • customer picks the locker:
  • reserve a slot at checkout
  • returns by customers: a deposit
  • with a courier pickup code
  • slot out of order: a flag the
  • strategy skips
  • temperature slots: a new
  • feature + strategy rule
  • many lockers: index free slots
  • per locker and size

Testing

The full code is below the player. The demo fills a small slot, spills the next small parcel into a medium slot, sends a large parcel to the depot when no large slot is left, uses a code once and rejects it the second time, moves a fake clock four days forward to expire a parcel, runs the return sweep, and lets ten couriers race for four fitting slots. Exactly four parcels are placed, in four different slots.

Run it
P1 (small) -> BLR1-S1
P2 (small) -> BLR1-M1 (size up)
P3 (large) -> BLR1-L1
P4 (large) -> no slot, depot
asha picks up: P1
same code again: wrong or used
ravi after 4 days: expired
sweep returned: [P2, P3]
Race: 10 parcels, 4 slots, placed 4

Say it like this

Here is the short version to say out loud. Lockers have slots, and a slot holds one immutable deposit: the parcel, its code and its expiry. Best fit is a strategy. Slots fill and empty with compare-and-set, so couriers never collide. Codes are secure random, unique among live parcels, and removed on use, so each works once. A daily sweep sends expired parcels back.

In the interview
  • "Lockers have slots; a slot
  • holds one immutable Deposit:
  • parcel, code, expiry. Best fit
  • is a strategy. Slots fill and
  • empty with compare-and-set.
  • Codes are secure random,
  • unique, and removed on use, so
  • they work once. A daily sweep
  • returns expired parcels."

Interview questions

How do you stop two couriers from putting parcels in the same slot?

Each slot holds its deposit in an AtomicReference and filling is compareAndSet(null, deposit). Only one courier succeeds; the other moves on to the next candidate slot, with no global lock.

How do you make a pickup code work only once?

Codes live in a concurrent map from code to slot, and pickup starts with an atomic remove. A second attempt, even at the same instant, finds nothing and is rejected.

Why keep the parcel, code and expiry in one Deposit record?

They always change together. Swapping one immutable record in and out of the slot with compare-and-set means a slot is never seen half-filled, such as having a parcel but no code.

Why does emptying use compareAndSet(deposit, null) instead of set(null)?

A slow operation could otherwise clear a newer parcel. Comparing against the exact deposit it read means a late pickup or sweep only empties the slot if it still holds that parcel.

How do you pick a slot for a parcel?

A SlotStrategy. Best fit takes lockers in the customer pincode, keeps free slots that fit and sorts smallest first, so small parcels do not use up the large slots that big parcels need.

How are uncollected parcels handled?

Each deposit carries an expiry. Pickup refuses expired codes, and a daily sweep empties expired slots with compare-and-set, removes their codes, lists the parcels for the courier and notifies the customer.

How do you keep the six-digit codes secure?

Generate them with SecureRandom, keep them unique among live parcels with putIfAbsent, make them single-use and expiring, lock the keypad after several wrong tries, never log them, and store a hash in a real system.

How would you scale to thousands of lockers?

Keep a free-slot index per locker and size so finding a slot is a lookup, not a scan, route each locker to one owner or use a database row per slot with a conditional update as the compare-and-set.