Java Smart Parking System: License Recognition, Cross-Day Billing, Contactless Pay & Auto Gate
This article details a production-ready Java 21 smart parking system using Spring Boot, MySQL, Redis, and MQTT, covering license plate deduplication, cross-day billing strategies, contactless payment idempotency, reliable gate control via MQTT, and offline edge architecture for network resilience.
Reading font

1. Core Data Models: Separating Sessions, Orders, and Device Events
The author argues that a single parking record table is insufficient once features like prepayment, exit timeout surcharges, contactless payment, and anomaly handling are added. Instead, the system requires at least seven core models:
parking_lot – lot info, capacity, business rules
parking_lane – entry/exit lanes and device bindings
parking_session – a vehicle's complete parking lifecycle
parking_fee_order – fee calculation, payment, refunds
parking_fee_rule – charging rules with versioning
parking_device_event – camera, loop detector, gate events
gate_command – gate control instructions and execution results
The parking_session table uses a MySQL generated column active_plate and a unique index uk_active_vehicle to ensure only one active session per plate per lot. Statuses are modeled as an enum: ENTRY_PENDING, PARKED, EXIT_PENDING, COMPLETED, CANCELLED. The author emphasizes that camera recognition ≠ entry and gate open ≠ exit; a reliable passage detector (loop sensor) must confirm physical passage before state transitions.
2. Handling Duplicate Camera Recognitions
Cameras may report the same plate multiple times within milliseconds. Two-layer idempotency is implemented:
Device event idempotency – unique constraint on (device_id, event_id) in parking_device_event.
Business idempotency – before creating a session, query for an active session with the same plate in the same lot. The Java service VehicleEntryService.handleEntry demonstrates this: it locks the device event row, parses the plate, checks sessionMapper.findActiveSession, and if found marks the event as duplicate. If not, it creates a PENDING_ENTRY session, inserts a gate open command, publishes a GateCommandCreatedEvent via outbox, and marks the event processed.
Concurrency is ultimately guarded by the database unique index uk_active_vehicle; on conflict the transaction rolls back, re-queries the active session, and processes the duplicate in a new transaction. Redis can cache recent plates to reduce DB load but cannot replace the DB constraint. The author also notes that a plate appearing at another entry while already parked may indicate recognition error or anomaly and should be escalated.
3. Flexible, Versioned Billing Rules
Billing rules are complex (free minutes, first hour price, incremental unit, daily cap, exit grace period, day/night rates, holiday pricing). Hard‑coding leads to massive if‑else chains. The solution: externalize rules as versioned JSON configuration, e.g.:
{ "ruleVersion": 3, "freeMinutes": 30, "firstPeriodMinutes": 60, "firstPeriodPrice": 5.00, "additionalPeriodMinutes": 30, "additionalPeriodPrice": 3.00, "dailyMaximum": 50.00, "exitGraceMinutes": 15, "billingCycle": "ROLLING_24_HOURS", "freeMode": "THRESHOLD_ONLY" }THRESHOLD_ONLYmeans free only if total stay ≤ free minutes; once exceeded, billing starts from entry time (not after deducting free minutes). A Java record ParkingFeeRule holds the parameters. The article provides a RollingDayFeeCalculator implementing a strategy where each rolling 24‑hour window is capped separately, and the initial free threshold applies only once per session. Concrete examples:
20 min → ¥0
31 min → ¥5
1 hr → ¥5
1 hr 1 min → ¥8
2 hr → ¥11
24 hr → ¥50
26 hr → ¥61 (50 + 11)
48 hr → ¥100
Different billing modes (calendar day, day/night) are implemented as separate ParkingFeeCalculator strategies selected by the rule's billingCycle. Time‑zone aware boundaries are used for calendar‑day modes; Instant / Duration for rolling windows to avoid DST issues. The session freezes the rule version at entry so price changes don't affect parked vehicles.
4. Prepayment, Exit Grace Period, and Incremental Settlement
A single paid flag is insufficient. A session may generate multiple parking_fee_order rows, each with billing_end_at, gross_fee, discount_amount, payable_amount, exit_valid_until. When a user prepay at 14:00 with a 15‑minute grace, leaving at 14:10 is free; leaving at 15:00 requires paying only the incremental fee (e.g., total ¥26 minus already paid ¥20 = ¥6). The quote method computes: payable = grossFee - discount - settledAmount, returning a ParkingFeeQuote with validUntil (30 seconds). Discounts are cumulative, not re‑granted per payment. Coupon reservation, write‑off, release, and refund are handled separately. Order creation locks the session, re‑validates the quote and existing orders to prevent duplicate orders from mini‑program, exit kiosk, and contactless service concurrently.
5. Contactless Payment: Authorization, Idempotency, and Unknown State Handling
Contactless payment requires a stored vehicle_payment_agreement linking user, plate, provider, and agreement number. The flow: exit detection → query agreement → create fee order → call provider's charge(agreementNo, amount) → handle callback. Critical: network timeout does not mean failure; the provider may have already charged. Payment statuses include CREATED, PROCESSING, UNKNOWN, SUCCESS, FAILED, CLOSED, REFUNDED. On UNKNOWN, the system must query the provider using the original merchant order number and follow the provider's idempotency/close protocol before allowing a new payment attempt. Callbacks verify signature, merchant ID, order number, amount, trade status, and use unique transaction ID for idempotency. Not all merchant accounts have contactless capability; it depends on provider permissions, industry qualification, and user authorization flow.
6. Reliable Gate Control: Commands, MQTT, and Passage Tokens
Gate control is an independent reliable command system. gate_command table stores commandId, sessionId, laneId, deviceId, commandType, passageToken (identifies the current vehicle passage cycle), status, retryCount, expiresAt, timestamps. Commands are sent via MQTT topic parking/{parkingLotId}/devices/{deviceId}/commands with QoS 1. Payload example:
{ "commandId": "GATE-CMD-202612010001", "commandType": "OPEN", "sessionId": "100086", "passageToken": "PASSAGE-EXIT-0038", "expiresAt": "2026-12-01T10:30:15Z" }Device reports execution on a separate topic. The system distinguishes command received , command executed , and vehicle actually passed . QoS 1 does not guarantee exactly‑once execution; device/edge must deduplicate by commandId and return previous result. Commands expire and are validated against the current passageToken to prevent stale commands opening the gate for a new vehicle. Retained MQTT messages must not be used for gate commands. Device authentication, topic ACL, and command legitimacy checks are required. Safety functions (anti‑crush, obstacle detection, emergency stop) remain on local controllers, not cloud.
7. Multi‑Exit Concurrency: Exit Attempts and Passage Tokens
Large lots have multiple exits; a vehicle may trigger recognition at two exits simultaneously. An VehicleExitAttempt record (attemptId, sessionId, laneId, passageToken, expiresAt) is created/updated per exit zone entry. authorizeExit locks the parking_session row, verifies the attempt is current, checks passage token matches the lane's current vehicle, confirms valid exit entitlement (payment within grace period), ensures no existing exit command for this attempt, marks session EXIT_PENDING, inserts gate command, and publishes event. Unique constraints on exit attempt + command prevent duplicate gate orders. If the driver switches exits, the old attempt must expire or be revoked before a new one is created. Session moves to COMPLETED only after confirmed vehicle passage, with SQL that checks status, lane, and passage token.
8. Accurate Space Counting: Reserved + Occupied, Not Just Redis INCR/DECR
Simple Redis counters drift due to duplicate/lost/out‑of‑order device events. The authoritative source is a parking_capacity table with total_spaces, occupied_spaces, reserved_spaces, version. Entry flow: atomic
UPDATE ... SET reserved_spaces = reserved_spaces + 1, version = version + 1 WHERE occupied_spaces + reserved_spaces < total_spaces. On confirmed entry (via loop sensor), another atomic update converts reserved → occupied. Exit reverses occupied. All updates run inside the session state‑transition transaction, bound to the specific session, so retries don't double‑count. A background job periodically reconciles capacity against active sessions and confirmed reservations; lots with per‑bay sensors can cross‑check. Fixed bays, maintenance bays, EV charging bays, and internal traffic are handled separately per operational rules.
9. Offline Edge Architecture for Network Partitions
Cloud connectivity cannot be assumed. The architecture splits: Edge gateway handles device protocol adaptation, local event caching, device control, safety detection, and offline passage policies. Cloud (Java) manages centralized rules, sessions, orders, operations, and reconciliation. During cloud outage, edge serves permit vehicles (monthly, fixed bay) and vehicles matching offline policies using locally cached authorizations. Temporary vehicles use manual terminals or approved offline policies; payments cannot be fabricated. Exceptional manual releases are logged with operator, reason, and passage details – not disguised as paid orders. On recovery, edge re‑uploads events by device event ID; cloud performs idempotent processing, session reconciliation, and fee discrepancy analysis. Device local timestamp, server receive time, and device sequence number are stored to reconstruct true passage order across devices.
10. Mandatory Test Scenarios Before Launch
The author lists ten critical test cases:
Same camera reports 10 recognition events → only one valid entry.
Two entries recognize same plate simultaneously → no duplicate active sessions.
Cross‑midnight, multi‑day, multi‑24‑hour cycles → fees match configured rules.
Prepayment exceeds grace period → only incremental fee charged.
Contactless payment timeout but actual charge succeeded → no duplicate charge.
Payment callback retried 10 times → no duplicate gate commands.
Device receives stale gate command → must not open for current vehicle.
Gate opens but vehicle doesn't pass → session not completed prematurely.
Loop sensor duplicate passage events → space count not double‑incremented.
Network outage and recovery → historical events re‑synced and reconciled.
Fee engine should use JUnit parameterized tests covering time boundaries (example CSV source shown). Database concurrency tested with Testcontainers + real MySQL. MQTT command delivery tested with a simulator injecting duplicates, delays, disconnects, reordering. Post‑launch monitoring: plate recognition anomaly rate, avg entry/exit latency, payment success rate, duplicate charge incidents, gate command success rate, space count deviation, device offline duration. Privacy: access control, audit logs, retention policies, de‑identification for plate/location/history data.
Closing Insight
The author concludes that a smart parking system integrates core Java enterprise techniques: rule engines, DB transactions, concurrency control, payment idempotency, IoT messaging, reliable delivery, distributed failure recovery. The key differentiator from pure software systems is that every DB state must match a physical world action: payment success ≠ gate open; gate open ≠ vehicle exited; vehicle exited ≠ all records synced. Building a demo takes days; making it run reliably in malls, hospitals, offices, and residential complexes for years demands rigorous handling of software‑reality inconsistency. The same patterns apply to smart access control, unmanned warehouses, EV charging, self‑service car wash, and other IoT device management platforms.
About this article
For attribution, corrections or content rights, contact