VOOZH about

URL: https://dev.to/machinecodingmaster/java-lld-amazon-locker-design-with-smallestfit-allocation-275k

⇱ Java LLD: Amazon Locker Design with SmallestFit Allocation - DEV Community


Java LLD: Amazon Locker Design with SmallestFit Allocation

Designing an Amazon Locker system is a favorite Low-Level Design (LLD) question at FAANG because it tests your ability to handle physical constraints and concurrency. If you cannot guarantee thread-safe slot allocation while minimizing wasted space, your design will fall apart under production load.

The Mistake Most Candidates Make

  • Naively picking the first available locker: This leads to massive spatial fragmentation, such as placing a small smartphone box into an extra-large locker, leaving zero room for actual oversized shipments.
  • Ignoring race conditions: Failing to make slot reservation atomic allows two delivery agents to simultaneously claim the same physical locker slot for different packages.
  • Tight coupling of business logic: Mixing package delivery status, locker state, and notification dispatching into a single monolithic class.

The Right Approach

  • Core mental model: Match packages to the absolute smallest compatible locker slot using a thread-confined SmallestFit algorithm.
  • Key entities/classes: Locker, Slot (Size: SMALL, MEDIUM, LARGE), LockerAssignmentStrategy, SmallestFitStrategy, LockerService.
  • Why it beats the naive approach: It maximizes overall locker utilization and revenue potential by keeping larger slots open for larger items.

Shameless plug: javalld.com has full LLD implementations with step-by-step execution traces — free to use while prepping.

The Key Insight (Code)

public class SmallestFitStrategy implements LockerAssignmentStrategy {
 @Override
 public synchronized Optional<LockerSlot> allocate(List<LockerSlot> slots, Package pkg) {
 return slots.stream()
 .filter(slot -> slot.isAvailable() && slot.getSize().canFit(pkg.getSize()))
 .min(Comparator.comparing(LockerSlot::getSize))
 .map(slot -> {
 slot.reserve();
 return slot;
 });
 }
}

Key Takeaways

  • SmallestFit Strategy: Always sort and filter available slots to find the tightest fit, preserving larger inventory for oversized goods.
  • Thread Confinement: Ensure that slot status transitions (e.g., AVAILABLE to RESERVED) are atomic to prevent race conditions during peak delivery hours.
  • Behavioral Decoupling: Use the Strategy pattern for allocation logic and the Factory pattern for locker creation to keep the system highly extensible.

Full working implementation with execution trace available at https://javalld.com/problems/amazon-locker