City-Wide EV Charging Network — Part B
Definitions
Geohash
- In plain English
- A geohash turns a latitude and longitude into a short string where nearby places share a prefix, making "near me" searches fast.
- Think of it like
- It is like postcodes, where nearby streets share the first characters.
Reconciliation
- In plain English
- Reconciliation is comparing two records of the same events and fixing any differences.
- Think of it like
- Like matching your receipts against your bank statement.
The brief
You will prevent double-booking, recover offline session records, and handle commands whose outcomes are initially unknown.
What it must do
- Reserve connectors for 15 minutes and support remote start or stop.
How well it must do it
- Never double-book a connector.
- Bill accurately after offline records are reconciled.
- Keep individual connectivity failures from disrupting healthy chargers.
Out of scope
- Hardware design and roaming.
Design walkthrough
Deep dive 1: reservations without double-booking
Use Module 3 constraints to enforce one blocking reservation per connector. Keep expired reservation records for history.
CREATE TABLE reservations (
id uuid PRIMARY KEY, connector_id bigint NOT NULL,
account_id bigint NOT NULL, request_key text NOT NULL,
state text NOT NULL CHECK
(state IN ('active','starting','charging','expired','ended')),
expires_at timestamptz NOT NULL,
UNIQUE (account_id, request_key)
);
CREATE UNIQUE INDEX one_blocking_reservation
ON reservations (connector_id)
WHERE state IN ('active','starting','charging');Do not put now() in the index predicate. Time passing does not remove an index entry; a transaction must change expired state.
- Lock the connector row, verify current availability, expire overdue active reservations, then insert the new reservation in one transaction.
- Every reserve and start path locks the same connector first. Start verifies owner and expiry before changing active to starting.
- Keep starting and charging reservations blocking until a confirmed rejection, confirmed stop, or reconciliation resolves them.
- Idempotency keys return the original reservation or command; reject the same key with a different request body.
Reservation expiry is not charging expiry. Starting consumes the reservation, and the connector remains occupied until the session ends.
Deep dive 2: devices that go offline
Expect a heartbeat every 30 seconds. Three missed intervals mean 3 × 30 = 90 seconds before marking status unknown.
A charger retains records while disconnected, then replays them; the backend either finalises one invoice or holds inconsistent sessions for investigation.
Require chargers to retain stable local session and sample IDs across restarts. An offline start cannot rely on a new backend-issued ID.
Use charger ID plus original session ID as the billing identity. Insert that identity and invoice atomically with a unique constraint.
Subtract validated cumulative start energy from end energy. Convert watt-hours to kWh by dividing by 1,000; apply the stored tariff and rounding rules.
Support offline continuation only when device capabilities and operator policy allow it. Missing final readings leave billing pending. Charge the final invoice with Module 5 idempotency; uncertain payments remain pending until resolved.
Deep dive 3: remote start with an uncertain outcome
Return accepted with a command ID and starting status. Persist the command before delivery and look up the current gateway owner.
A start request may confirm immediately, confirm after a retry, or remain unknown until a later session report resolves it.
Module 5 timeouts bound waiting, not physical actions. After 20 seconds, retry once only when device-side duplicate suppression is guaranteed.
Reuse the backend command identity, but do not assume the protocol message ID guarantees device idempotency. Otherwise query status before resending.
Wait another 20 seconds after a safe retry, then tell the driver the start is unconfirmed. Keep the connector blocked until confirmation or reconciliation.
A Module 5 breaker per site stops repeated calls during connectivity failures. Bound stop retries too; show unconfirmed until a session-ending event arrives.
Deep dive 4: nearby chargers
Example location index keys:
area:tdr1
area:tdr2
Read the centre cell and neighbouring cells.
Filter candidates by actual distance.
Join connector status and last-seen timestamps.A location lookup reads nearby indexed cells, removes candidates beyond the requested distance, and adds timestamped connector status.
A prefix alone misses nearby chargers across cell boundaries. Use Module 3 indexing, then check actual distance.
Cache popular-area candidate lists for ten seconds. Recheck availability in the reservation transaction; a map result never grants ownership.
What breaks, and what happens
| Failure | Effect | Mitigation |
|---|---|---|
| Gateway dies | Live sockets close and commands become uncertain. | Chargers reconnect; update ownership generation and resolve pending commands before retrying. |
| Event stream falls behind | Map status grows stale. | Show observation and last-seen times; mark stale status unknown rather than available. |
| Relational database fails over | New reservations and billing pause. | Resume only after safe primary ownership; reject conflicting writes during uncertainty. |
| Site loses connectivity | Live commands and readings stop. | Continue permitted local sessions, retain records, and reconcile on reconnect. |
Monitoring
- Measure online percentage, heartbeat gaps, command latency, confirmed starts, and unknown outcomes.
- Watch stream lag and last-observation age separately from socket connectivity.
- Alert on reconciliation mismatches, missing final readings, and long-pending bills.
- Module 5 observability makes unresolved physical actions visible rather than hiding them as successful requests.
The 30-second map target applies to received updates on healthy paths. Three-heartbeat failure detection takes 90 seconds plus processing delay.
Replay old measurements into history without overwriting newer live status. Compare per-connector event order and observation time before changing the status cache.
At ten times the scale
At 80,000 chargers, meter sampling becomes 80,000 ÷ 30 ≈ 2,667 samples per second and 230,400,000 rows per day.
Add gateways and stream partitions by charger ID. Shard meter history by charger and time while preserving per-session record identity.
Regional deployments reduce device latency. Keep one authoritative region for each connector and invoice; cross-region partitions must not duplicate ownership.
Design decisions
What prevents double-booking?
Our choice
Use a database constraint and connector transaction. This applies Module 3 transactions and Module 5 idempotency.
Why not the alternatives
- Check availability only in application codeConcurrent requests can both pass a check before either reserves.
How do offline sessions reach billing safely?
Our choice
Replay original identities and reconcile before billing. This combines Module 4 events with Module 5 idempotency.
Why not the alternatives
- Discard old records or bill each replayDiscarding loses energy records; billing every replay charges twice.
How do remote commands fail safely?
Our choice
Use bounded waits, safe retries, and site breakers from Module 5. Keep uncertain starts blocked.
Why not the alternatives
- Release the connector as soon as a timeout expiresThe physical start may have happened despite a lost reply.
Which operations remain available during a partition?
Our choice
Serve labelled stale status but pause ownership writes without authority. This applies Module 5 CAP and consistency.
Why not the alternatives
- Treat cached availability as permission to reserveStale data cannot safely grant exclusive connector ownership.
What should operators watch?
Our choice
Track freshness, command uncertainty, and billing mismatches using Module 5 observability.
Why not the alternatives
- Measure only successful HTTP responsesAn accepted request may still have an unresolved physical outcome.
Trade-offs
Pros
- Constraints protect connector ownership.
- Stable identities prevent duplicate billing.
- Uncertain commands remain visible and recoverable.
Cons
- Conservative blocking can delay the next driver.
- Offline recovery depends on retained device records.
- Cached maps can lag physical reality.
Use when
- Unreliable device networks with money and exclusive reservations.
Avoid when
- Devices without durable records cannot support this offline billing guarantee.
Quick check
Takeaways
- Let database constraints prevent double-booking.
- Treat offline status as unknown, then replay and reconcile using stable identities.
- Bound command waits and retries while preserving uncertain ownership.