Building a Production-Grade Smart Parcel Locker System with Java: Concurrency, MQTT & Offline Resilience
This article details the design of a production-ready smart parcel locker system using Java 21, Spring Boot, MySQL, Redis, and MQTT, covering domain modeling, concurrent compartment allocation with FOR UPDATE SKIP LOCKED, deposit/pickup confirmation workflows, secure pickup code generation, remote door opening via MQTT, timeout billing, reservation recovery, and offline operation with edge controllers.
Reading font

1. Independent Business Models for Locker, Compartment, and Parcel
Many developers start with a single compartment table containing tracking number, phone, pickup code, and status. This works for demos but fails when handling repeat deposits, timeouts, maintenance, and history queries. A compartment is a long-lived physical resource; each deposit/pickup is a distinct business record with its own lifecycle.
The system requires at least seven core data models:
locker_station : site, address, operator
locker_device : device ID, online status
locker_compartment : compartment number, size, resource status, door status
parcel_storage : parcel storage record and lifecycle
pickup_credential : pickup code, expiry, usage status
locker_command : open-door command and execution result
locker_device_event : door, sensor, and device reported events
Compartment table design (MySQL):
CREATE TABLE locker_compartment (</code><code> id BIGINT PRIMARY KEY,</code><code> locker_id BIGINT NOT NULL,</code><code> compartment_no VARCHAR(32) NOT NULL,</code><code> size_type VARCHAR(16) NOT NULL,</code><code> resource_status VARCHAR(20) NOT NULL,</code><code> door_status VARCHAR(20) NOT NULL,</code><code> current_storage_id BIGINT NULL,</code><code> allocation_epoch BIGINT NOT NULL DEFAULT 0,</code><code> reserved_until DATETIME(3) NULL,</code><code> updated_at DATETIME(3) NOT NULL,</code><code> UNIQUE KEY uk_locker_compartment (locker_id, compartment_no),</code><code> INDEX idx_available_compartment (locker_id, resource_status, size_type)</code><code>);Resource status (whether a compartment can be assigned) and door status (physical open/closed) must be separate. Mixing them makes device exception handling extremely difficult.
public enum CompartmentStatus {</code><code> AVAILABLE, RESERVED, OCCUPIED, RELEASING, FAULT, DISABLED</code><code>}</code><code>public enum DoorStatus {</code><code> OPEN, CLOSED, UNKNOWN</code><code>}A closed door does not mean the compartment is empty; an open door does not mean the parcel is gone. The resource status flow is: AVAILABLE → RESERVED → OCCUPIED → RELEASING → AVAILABLE (with FAULT/DISABLED as side states). The critical business invariant: at any time, a compartment belongs to at most one valid parcel storage record.
2. Concurrent Compartment Allocation for 10 Couriers
Assume a locker with three sizes: Small (40 total, 8 free), Medium (35 total, 12 free), Large (25 total, 5 free). Couriers scan a tracking number, choose parcel size, and the system auto-assigns a compartment. Small parcels should prefer small compartments; only fall back to larger sizes when necessary (best-fit strategy). Large parcels cannot go into smaller compartments.
Define compartment sizes with a level hierarchy:
public enum CompartmentSize {</code><code> SMALL(1), MEDIUM(2), LARGE(3);</code><code> private final int level;</code><code> CompartmentSize(int level) { this.level = level; }</code><code> public int level() { return level; }</code><code> public boolean canHold(CompartmentSize parcelSize) {</code><code> return level >= parcelSize.level();</code><code> }</code><code>}The real challenge is concurrency: two Spring Boot instances may query the same free compartment. A simple select-then-update leads to double allocation. Use MySQL 8's FOR UPDATE SKIP LOCKED to atomically lock and skip already-locked rows.
SELECT id, locker_id, compartment_no, allocation_epoch</code><code>FROM locker_compartment</code><code>WHERE locker_id = #{lockerId}</code><code> AND resource_status = 'AVAILABLE'</code><code> AND door_status = 'CLOSED'</code><code> AND size_type IN ('SMALL', 'MEDIUM', 'LARGE')</code><code>ORDER BY CASE size_type</code><code> WHEN 'SMALL' THEN 1</code><code> WHEN 'MEDIUM' THEN 2</code><code> WHEN 'LARGE' THEN 3</code><code> END, id</code><code>LIMIT 1</code><code>FOR UPDATE SKIP LOCKED;SKIP LOCKEDlets a transaction jump over rows locked by other transactions, avoiding hotspot contention. Java allocation logic (simplified):
@Service</code><code>public class LockerAllocationService {</code><code> private final CompartmentMapper compartmentMapper;</code><code> private final ParcelStorageMapper storageMapper;</code><code> private final LockerCommandMapper commandMapper;</code><code> private final OutboxMapper outboxMapper;</code><code> private final CourierPermissionService permissionService;</code><code> private final IdGenerator idGenerator;</code><code> private final Clock clock;</code><code> @Transactional(isolation = Isolation.READ_COMMITTED)</code><code> public AllocationResult allocate(long courierId, StoreParcelCommand request) {</code><code> permissionService.requireStorePermission(courierId, request.lockerId());</code><code> ParcelStorage existing = storageMapper.findByRequestId(courierId, request.requestId());</code><code> if (existing != null) {</code><code> verifySameRequest(existing, request);</code><code> return AllocationResult.from(existing);</code><code> }</code><code> long storageId = idGenerator.nextId();</code><code> storageMapper.insertCreating(storageId, courierId, request);</code><code> Compartment compartment = compartmentMapper.findAvailableForUpdate(request.lockerId(), request.parcelSize());</code><code> if (compartment == null) { throw new NoAvailableCompartmentException(); }</code><code> Instant expiresAt = clock.instant().plusSeconds(120);</code><code> long epoch = compartment.getAllocationEpoch() + 1;</code><code> int updated = compartmentMapper.reserve(compartment.getId(), storageId, epoch, expiresAt);</code><code> if (updated != 1) { throw new CompartmentUnavailableException(); }</code><code> storageMapper.markReserved(storageId, compartment.getId(), epoch, expiresAt);</code><code> LockerCommand command = LockerCommand.openForDeposit(storageId, compartment.getId(), epoch, expiresAt);</code><code> commandMapper.insert(command);</code><code> outboxMapper.insert(LockerCommandCreatedEvent.from(command));</code><code> return new AllocationResult(storageId, compartment.getCompartmentNo(), expiresAt);</code><code> }</code><code>}Reservation uses a conditional update:
UPDATE locker_compartment</code><code>SET resource_status = 'RESERVED',</code><code> current_storage_id = #{storageId},</code><code> allocation_epoch = #{epoch},</code><code> reserved_until = #{expiresAt},</code><code> updated_at = NOW(3)</code><code>WHERE id = #{compartmentId}</code><code> AND resource_status = 'AVAILABLE'</code><code> AND door_status = 'CLOSED';All three steps (reserve compartment, create storage record, create open command) must run in one DB transaction. A unique constraint on courier_id + request_id prevents duplicate storage records; catch duplicate key exception and return the existing result. If SKIP LOCKED finds no row, retry a few times before returning failure — absence may mean the candidate is temporarily locked, not that the locker is full.
3. When Is a Deposit Truly Complete?
After allocating compartment 28 and sending an open command, the courier might open the door but not place the parcel inside. If the system marks the parcel as stored upon door-open and sends a pickup notification, the user will find an empty compartment.
Deposit success requires full device and business confirmation. If the compartment has presence sensors (infrared, weight), use sensor data as proof. Without sensors, rely on door-close event plus explicit courier confirmation — but this only proves process completion, not physical presence.
Java handler for deposit confirmation:
@Transactional</code><code>public void confirmDeposit(DepositConfirmedEvent event) {</code><code> ParcelStorage storage = storageMapper.lockById(event.storageId());</code><code> if (storage == null) { throw new StorageNotFoundException(); }</code><code> if (storage.getStatus() == StorageStatus.STORED) { return; }</code><code> Compartment compartment = compartmentMapper.lockById(storage.getCompartmentId());</code><code> if (storage.getStatus() != StorageStatus.RESERVED</code><code> || !Objects.equals(compartment.getCurrentStorageId(), storage.getId())</code><code> || compartment.getAllocationEpoch() != event.allocationEpoch()) {</code><code> throw new InvalidStorageStateException();</code><code> }</code><code> depositEvidenceService.requireValid(storage, compartment, event);</code><code> storageMapper.markStored(storage.getId(), event.confirmedAt());</code><code> compartmentMapper.markOccupied(compartment.getId(), storage.getId());</code><code> PickupCredential credential = credentialService.create(storage);</code><code> outboxMapper.insert(ParcelStoredEvent.of(storage.getId(), credential.getId()));</code><code>}Only after storage status becomes STORED does the system generate a valid pickup credential and trigger notifications. Notifications are sent after transaction commit; failures are retried without reverting the stored parcel.
4. Secure 6-Digit Pickup Code Generation
Naive random generation ( new Random().nextInt(900000) + 100000) ignores collisions, expiry, attempt limits, device scope, and post-use state. Six digits yield only 1,000,000 combinations — suitable as a short credential scoped to a single locker with rate limiting, not as a global platform-wide token.
Pickup credential table with MySQL generated column for active-code uniqueness:
CREATE TABLE pickup_credential (</code><code> id BIGINT PRIMARY KEY,</code><code> storage_id BIGINT NOT NULL,</code><code> locker_id BIGINT NOT NULL,</code><code> code_digest BINARY(32) NOT NULL,</code><code> encrypted_code VARBINARY(256) NULL,</code><code> status VARCHAR(20) NOT NULL,</code><code> expires_at DATETIME(3) NOT NULL,</code><code> used_at DATETIME(3) NULL,</code><code> active_digest BINARY(32)</code><code> GENERATED ALWAYS AS (</code><code> CASE WHEN status IN ('ACTIVE','IN_USE') THEN code_digest ELSE NULL END</code><code> ) STORED,</code><code> UNIQUE KEY uk_active_pickup_code (locker_id, active_digest),</code><code> INDEX idx_storage_credential (storage_id, status)</code><code>);The generated column + unique key ensures no two active credentials share the same digest within a locker. Used/revoked credentials are excluded.
Generate codes with SecureRandom:
@Component</code><code>public class PickupCodeGenerator {</code><code> private final SecureRandom random = new SecureRandom();</code><code> public String generate() {</code><code> return "%06d".formatted(random.nextInt(1_000_000));</code><code> }</code><code>}Even with secure random, collisions can happen; rely on the DB unique constraint to detect and retry. Storing a plain SHA-256 hash is unsafe because an attacker can offline-enumerate all 1M combinations. Instead, use HMAC-SHA256 with a server-side secret key:
public byte[] digest(long lockerId, String code, SecretKey secretKey)</code><code> throws GeneralSecurityException {</code><code> Mac mac = Mac.getInstance("HmacSHA256");</code><code> mac.init(secretKey);</code><code> String value = lockerId + ":" + code;</code><code> return mac.doFinal(value.getBytes(StandardCharsets.UTF_8));</code><code>}The HMAC key must be managed by a separate key management system, not stored alongside digests. Key rotation requires versioning and handling legacy credential validation. If the app lets users view the original code, store it encrypted (not via HMAC). The pickup API must enforce per-device, per-locker, and per-source attempt limits. For high-value parcels, require authenticated app scan or additional identity verification.
5. Remote Door Opening via MQTT
After the user enters a valid pickup code, the backend must locate the parcel and command the specific device to open the specific compartment. A naive
lockerClient.openDoor(...); storageRepository.markPickedUp(...);treats the device request as the final result — dangerous because the command may be lost, the device may not receive it, the response may be lost, or the door may open but the parcel remains.
Open-door must be an independent command lifecycle. Command table:
CREATE TABLE locker_command (</code><code> id BIGINT PRIMARY KEY,</code><code> command_id VARCHAR(64) NOT NULL,</code><code> locker_id BIGINT NOT NULL,</code><code> compartment_id BIGINT NOT NULL,</code><code> storage_id BIGINT NOT NULL,</code><code> allocation_epoch BIGINT NOT NULL,</code><code> command_type VARCHAR(32) NOT NULL,</code><code> status VARCHAR(20) NOT NULL,</code><code> retry_count INT NOT NULL DEFAULT 0,</code><code> expires_at DATETIME(3) NOT NULL,</code><code> created_at DATETIME(3) NOT NULL,</code><code> executed_at DATETIME(3) NULL,</code><code> UNIQUE KEY uk_command_id (command_id),</code><code> INDEX idx_command_recovery (status, expires_at)</code><code>);Command statuses:
CREATED, SENT, ACKNOWLEDGED, EXECUTED, FAILED, EXPIRED, UNKNOWN.
Devices connect via MQTT long-lived connections. Each device subscribes to its own command topic: locker/devices/{deviceId}/commands. Cloud publishes:
{</code><code> "commandId": "CMD-202612020001",</code><code> "commandType": "OPEN_FOR_PICKUP",</code><code> "storageId": "100086",</code><code> "compartmentNo": "028",</code><code> "allocationEpoch": 18,</code><code> "expiresAt": "2026-12-02T08:30:15Z"</code><code>}Device reports result:
{</code><code> "eventId": "EVENT-30001",</code><code> "commandId": "CMD-202612020001",</code><code> "compartmentNo": "028",</code><code> "allocationEpoch": 18,</code><code> "result": "SUCCESS",</code><code> "doorStatus": "OPEN"</code><code>}
MQTT QoS 1 guarantees at-least-once delivery, but duplicates can occur. The device controller must deduplicate using commandId and persist execution records across restarts. Commands have an expiry; do not use retained messages to avoid executing stale commands after reconnect. Each locker must have its own device identity and MQTT credentials — no shared credentials, no cross-subscription.
6. Door Opened but Parcel Not Taken — Can the Compartment Be Released?
This is a critical business problem. User opens compartment 28, realizes they brought the wrong phone, closes the door without taking the parcel. If the system auto-releases on door-close, the next courier could be assigned the same compartment while the original parcel is still inside.
Pickup must have at least three stages:
PICKUP_PENDING : identity verified, awaiting door open
PICKUP_OPENED : door successfully opened
PICKED_UP : pickup confirmation conditions satisfied
For lockers with presence sensors, only transition to
PICKED_UP</strong> when door closes AND sensor confirms empty. Java handler:</p><pre><code>@Transactionalpublic void confirmPickup(PickupConfirmedEvent event) {ParcelStorage storage = storageMapper.lockById(event.storageId());if (storage.getStatus() == StorageStatus.PICKED_UP) { return; }Compartment compartment = compartmentMapper.lockById(storage.getCompartmentId());if (storage.getStatus() != StorageStatus.PICKUP_OPENED|| !Objects.equals(compartment.getCurrentStorageId(), storage.getId())|| compartment.getAllocationEpoch() != event.allocationEpoch()) {throw new InvalidPickupStateException();}pickupEvidenceService.requireValid(storage, compartment, event);int updated = compartmentMapper.release(compartment.getId(), storage.getId(), event.allocationEpoch());if (updated != 1) { throw new IllegalStateException("Compartment ownership mismatch"); }storageMapper.markPickedUp(storage.getId(), event.confirmedAt());credentialMapper.consumeByStorageId(storage.getId());outboxMapper.insert(ParcelPickedUpEvent.of(storage.getId()));}Release SQL includes the original storage ID and allocation epoch:
UPDATE locker_compartment</code><code>SET resource_status = 'AVAILABLE',</code><code> current_storage_id = NULL,</code><code> reserved_until = NULL,</code><code> updated_at = NOW(3)</code><code>WHERE id = #{compartmentId}</code><code> AND current_storage_id = #{storageId}</code><code> AND allocation_epoch = #{epoch}</code><code> AND resource_status = 'RELEASING'</code><code> AND door_status = 'CLOSED';The allocation_epoch acts as a fencing token. Suppose compartment 28 held parcel A (epoch 18). After pickup, it's reassigned to parcel B (epoch 19). If a delayed event for parcel A arrives later, the epoch mismatch prevents it from releasing parcel B's compartment. Without the epoch, a stale message could free a currently occupied compartment. If the locker lacks presence sensors, the system cannot guarantee the parcel was removed on door-close. It must rely on explicit user confirmation, door events, and manual exception handling, acknowledging the hardware limitation.
7. Timeout Billing After 24 Hours
Example fee rules: free 24 hours, then 0.50 CNY per 12 hours (ceiling), max 3 CNY per stay, 15-minute grace period after payment. Fee rules should be versioned and attached to the storage record at deposit time, not hardcoded in the pickup API. Java calculation using Duration and BigDecimal :
public record StorageFeeRule(</code><code> long freeHours,</code><code> long billingPeriodHours,</code><code> BigDecimal unitPrice,</code><code> BigDecimal maximumFee</code><code>) {}</code><code>public class StorageFeeCalculator {</code><code> public BigDecimal calculate(Instant storedAt, Instant pickupAt, StorageFeeRule rule) {</code><code> if (pickupAt.isBefore(storedAt)) { throw new IllegalArgumentException("Pickup before storage"); }</code><code> if (rule.freeHours() < 0 || rule.billingPeriodHours() <= 0</code><code> || rule.unitPrice().signum() < 0 || rule.maximumFee().signum() < 0) {</code><code> throw new IllegalArgumentException("Invalid fee rule");</code><code> }</code><code> Duration storedDuration = Duration.between(storedAt, pickupAt);</code><code> Duration freeDuration = Duration.ofHours(rule.freeHours());</code><code> if (storedDuration.compareTo(freeDuration) <= 0) {</code><code> return BigDecimal.ZERO.setScale(2);</code><code> }</code><code> Duration overtime = storedDuration.minus(freeDuration);</code><code> long periodSeconds = Duration.ofHours(rule.billingPeriodHours()).getSeconds();</code><code> long units = overtime.getSeconds() / periodSeconds;</code><code> if (overtime.getSeconds() % periodSeconds != 0 || overtime.getNano() != 0) {</code><code> units++;</code><code> }</code><code> BigDecimal fee = rule.unitPrice().multiply(BigDecimal.valueOf(units));</code><code> return fee.min(rule.maximumFee()).setScale(2, RoundingMode.UNNECESSARY);</code><code> }</code><code>}Example calculations:
12 hours → 0 CNY
24 hours → 0 CNY
24 hours 1 minute → 0.50 CNY
36 hours → 0.50 CNY
48 hours → 1 CNY
72 hours → 2 CNY
96 hours → 3 CNY (cap)
120 hours → 3 CNY
Real systems also need free policies, member benefits, fee waivers, and suspension during device faults. Record confirmed unavailability periods and deduct them per operational rules. Separate settlement models for deposit fees, courier compartment fees, and recipient overtime fees. Paid pickups get a grace period; reopening within that period must not recharge.
8. Auto-Recovering Abandoned Reservations
Courier reserves a compartment but doesn't deposit within 2 minutes (e.g., gets a phone call). If the compartment stays RESERVED , the locker appears full despite empty slots. Use Redis Sorted Set for reservation timeouts:
public void scheduleReservationTimeout(long storageId, Instant expiresAt) {</code><code> redisTemplate.opsForZSet().add("locker:reservation:timeout", String.valueOf(storageId), expiresAt.toEpochMilli());</code><code>}A background worker polls expired entries and checks. However, timeout doesn't mean immediate release: the courier may have placed the parcel but the device was offline and couldn't report success. Releasing blindly could cause two parcels in one compartment.
Recovery must verify actual device state. Confirm the original open command has executed or reliably expired before releasing. If the device is offline, door status unknown, or sensor faulty, mark the compartment as pending investigation rather than force-releasing for utilization. Redis timeout index improves scheduling efficiency, but MySQL's reserved_until is the authoritative record. Periodic DB scans guard against Redis restarts or lost messages leaving compartments stuck forever.
9. Offline Pickup When the Locker Loses Connectivity
Lockers in residential areas, offices, schools, and outdoors face network outages, server downtime, and carrier fluctuations. If every open requires a round-trip to Spring Boot, a network break paralyzes the locker. Mature designs insert a local edge controller between cloud and hardware. An embedded Linux board or storage-capable controller manages locks via RS485/CAN/vendor protocol and communicates with cloud via MQTT. The edge controller handles state collection, command validation, door control, event persistence, and offline recovery. For offline pickup, the cloud pre-issues short-lived offline pickup grants to specific devices:
public record OfflinePickupGrant(</code><code> String grantId,</code><code> long lockerId,</code><code> long compartmentId,</code><code> long storageId,</code><code> long allocationEpoch,</code><code> Instant expiresAt,</code><code> String keyId</code><code>){}The grant is digitally signed; the locker verifies with a trusted public key. If using signed QR codes, the device must persist consumed grantId s to prevent reuse. Offline grants are not a bulk download of all pickup codes — they are scoped to a specific compartment, epoch, and expiry, preventing expired grants from affecting other parcels. Inherent limitation: during offline, the cloud cannot revoke already-issued grants. Therefore, grant validity must be short. Parcels with unpaid fees, disputes, or in exception flows should be excluded from offline auto-pickup. Upon reconnection, the device uploads locally persisted pickup events (with unique event IDs). The server reconciles using storage record, compartment epoch, and event sequence. If safe confirmation is impossible, fall back to customer service or verified manual override — never bypass permission checks.
10. Overall Architecture for a Smart Parcel Locker Platform
For a first commercial version, avoid over-splitting into dozens of microservices. A modular Spring Boot monolith plus MQTT broker, Redis, MySQL, and edge controllers suffices.
MySQL stores critical data: compartment ownership, parcel records, pickup credentials, payment ledgers, device commands. Redis handles online status, timeout indexes, query caches, rate limiting. MQTT handles real-time cloud-device messaging; a message queue handles notifications, command publishing, and compensation. The edge controller bridges Java business logic and physical hardware: validates compartment epoch, drives electronic locks, collects door states, and buffers unsent events. Scale example: 10,000 lockers, 30-second heartbeat → ~333 msgs/sec. 100 compartments each → 1M physical compartments. Not all data needs real-time MySQL writes. Heartbeats and online status stay in Redis or a monitoring system; deposit, pickup, and authorization events must be durably persisted. Key pre-launch validation scenarios (test with Testcontainers + real MySQL/Redis/MQTT, simulate devices in Java/Python):
100 couriers simultaneously request compartments — no duplicate allocation.
Duplicate deposit request — cannot occupy multiple compartments.
Door opens but parcel not placed — no false pickup notification.
Same pickup code used concurrently — only one valid pickup session.
Duplicate open-door command delivery — no unauthorized re-open.
User opens door but doesn't take parcel — compartment not auto-released.
Delayed historical device event — does not affect new allocation epoch.
Legitimate offline operations during outage — sync accurately after reconnect.
Payment gateway timeout — no double charge.
Redis/app restart — recover timeout tasks and incomplete commands.
These tests can run without physical hardware; integrate real lock controllers, door sensors, and edge controllers only for final pre-launch validation.
Conclusion
A smart parcel locker appears to be just a cabinet with electronic locks, but it integrates core Java enterprise capabilities: dynamic resource allocation, database concurrency control, one-time credentials, state machines, reliable messaging, IoT communication, billing engines, and distributed fault recovery. This architecture extends beyond parcel lockers. Replace parcels with office supplies → smart supply cabinet; with hotel luggage → self-service luggage locker; with shared equipment → smart tool cabinet, shared charging station, unmanned warehouse. The underlying technical model is identical: physical resource management, temporary occupation, identity verification, remote authorization, device execution confirmation, and resource release. For Java developers, the real asset is a reusable business architecture that interacts with real devices — not merely calling a hardware vendor's unlock API. Sending an open-door command only proves the system requested the door to open; a device reporting success only proves the door opened. Only when the parcel is confirmed taken and the compartment meets reuse conditions is the pickup business truly complete.
About this article
For attribution, corrections or content rights, contact