Design the backend behind an EV charging network: OCPP events from chargers, session state, meter values, tariffs with idle fees, payment holds and captures, and roaming hooks, built by hand on AWS or in TypeScript with Encore in your own account.

An EV charging session is a small financial transaction with a physical device in the middle. The driver taps a card or an app, the charger asks the backend whether to start, and energy flows for forty minutes while the charger reports meter readings.
Then the car finishes but stays plugged in, and someone has to be charged the right amount for energy, time and idling, with a receipt that matches what the charger measured. Chargers lose connectivity, reboot mid-session and resend messages, and the backend has to produce one correct bill anyway.
This guide designs the session backend: charger events, the session state machine, meter values, tariffs and payment. It starts with a hand-built version on AWS, then builds it in TypeScript with Encore, with the data in your own AWS or GCP account.
Most chargers talk to the backend, called a charging station management system, over the Open Charge Point Protocol from the Open Charge Alliance: JSON messages over a WebSocket that the charger keeps open. In OCPP 1.6 the session is framed by StartTransaction, periodic MeterValues and StopTransaction; OCPP 2.0.1 folds them into TransactionEvent messages with Started, Updated and Ended types. Either way, the charger can buffer messages while offline and send them on reconnect, so the backend sees late and repeated events.
Keep the socket layer separate from session logic, with a small gateway that owns the connections (heartbeats, reconnects, which instance holds which charger, sending remote start and stop commands), translates OCPP frames into normalized events with the charger ID, connector, transaction ID and the charger's timestamp, and forwards them to the session service. Session logic then deals with one event format whichever OCPP version a charger speaks.
Store one row per session keyed by charger and transaction ID, with a state, the authorization used and a snapshot of the tariff that applied at start. Apply events with a guard on the current state, so a repeated Started is a no-op and an Ended that arrives before a buffered Updated still closes the session. Billing waits five minutes after ended_at so late meter values that arrive in that window are included in the total; readings after billed_at stay on the record but do not change the captured amount. Keep meter readings append-only, deduplicated on session plus timestamp, and compute energy from the first and last register readings rather than summing deltas, since a missing message in the middle then costs nothing.
CREATE TABLE sessions (
id BIGSERIAL PRIMARY KEY,
charger_id TEXT NOT NULL,
transaction_id TEXT NOT NULL,
connector INT NOT NULL,
state TEXT NOT NULL, -- charging, suspended, finishing, completed
auth_ref TEXT NOT NULL,
tariff JSONB NOT NULL,
started_at TIMESTAMPTZ NOT NULL,
charging_ended_at TIMESTAMPTZ,
ended_at TIMESTAMPTZ,
energy_wh BIGINT,
amount_cents BIGINT,
billed_at TIMESTAMPTZ,
UNIQUE (charger_id, transaction_id)
);
CREATE TABLE meter_values (
session_id BIGINT NOT NULL REFERENCES sessions(id),
measured_at TIMESTAMPTZ NOT NULL,
register_wh BIGINT NOT NULL,
power_w INT,
PRIMARY KEY (session_id, measured_at)
);
Price the session with the tariff snapshot stored at start, not the tariff in effect when it ends, so a price change at midnight never surprises a driver mid-session. A typical tariff has a price per kWh, sometimes a price per minute, a session fee, and an idle fee that starts a grace period after charging stops while the car stays connected; record charging_ended_at separately from ended_at for that reason.
For drivers paying by card, place a hold for an estimated maximum when the session starts and capture the final amount when it ends, releasing the rest. Stripe documents this flow as separate authorization and capture, with limits on how long a hold stays valid. In the EU, the Alternative Fuels Infrastructure Regulation requires operators of publicly accessible chargers to let drivers recharge on an ad hoc basis, without registering or entering a contract, so the backend needs a card path alongside RFID and app accounts. Roaming partners, usually connected through OCPI, need session and CDR updates; publish them from the same session events.
Run the OCPP gateway on ECS behind a Network Load Balancer, which passes long-lived WebSockets through without idle disconnects as long as the charger heartbeats. The gateway posts normalized events to a session service on ECS, which writes to RDS for PostgreSQL and sends a message per closed session to SQS. A pricing and payment worker computes the amount, captures the hold through the payment provider and publishes to SNS, which fans out to the driver app notifications and an OCPI worker. Each service needs an IAM role, a security group and a dead-letter queue, and the session service needs idempotent handlers for repeated charger events.
Encore brings infrastructure from code to the session service, which is where the business rules live. The gateway forwards events to an authenticated Encore endpoint, with the gateway's own credential checked by an auth handler; the database and the session events topic are declared in TypeScript, and Encore provisions RDS, SNS and SQS in your own AWS account, or Cloud SQL and Pub/Sub on GCP, and Encore provisions an IAM role for the service, or a service account on GCP. encore run starts Postgres and in-memory Pub/Sub, so you can replay a recorded charger log through the endpoint and see the session, the price and the payment events in the local trace.
Run in your terminal to get started locally.
// sessions/sessions.ts
import { api } from "encore.dev/api";
import { CronJob } from "encore.dev/cron";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
const db = new SQLDatabase("charging", { migrations: "./migrations" });
interface ChargerEvent {
chargerId: string;
transactionId: string;
connector: number;
type: "started" | "updated" | "charging_stopped" | "ended";
at: string; // charger timestamp
registerWh?: number; // meter register reading
authRef?: string;
}
export const sessionCompleted = new Topic<{ sessionId: number }>("session-completed", {
deliveryGuarantee: "at-least-once",
});
// Called by the OCPP gateway for every normalized charger event.
// The app's auth handler accepts only the gateway's credential.
export const chargerEvent = api(
{ expose: true, auth: true, method: "POST", path: "/charger-events" },
async (e: ChargerEvent): Promise<void> => {
if (e.type === "started") {
await db.exec`
INSERT INTO sessions (charger_id, transaction_id, connector, state, auth_ref, tariff, started_at)
VALUES (${e.chargerId}, ${e.transactionId}, ${e.connector}, 'charging', ${e.authRef ?? "unknown"},
(SELECT tariff FROM charger_tariffs WHERE charger_id = ${e.chargerId}), ${e.at})
ON CONFLICT (charger_id, transaction_id) DO NOTHING`;
}
const s = await db.queryRow<{ id: number; state: string }>`
SELECT id, state FROM sessions WHERE charger_id = ${e.chargerId} AND transaction_id = ${e.transactionId}`;
if (!s) return; // event for an unknown session; the gateway logs and alerts
if (e.registerWh !== undefined) {
await db.exec`
INSERT INTO meter_values (session_id, measured_at, register_wh)
VALUES (${s.id}, ${e.at}, ${e.registerWh}) ON CONFLICT DO NOTHING`;
}
if (e.type === "charging_stopped" && s.state === "charging") {
await db.exec`UPDATE sessions SET state = 'finishing', charging_ended_at = ${e.at} WHERE id = ${s.id}`;
}
if (e.type === "ended") {
await db.exec`
UPDATE sessions SET state = 'completed', ended_at = ${e.at}
WHERE id = ${s.id} AND state <> 'completed'`;
}
},
);
// Called by the cron job every minute; safe to run again.
export const finalizeBilling = api({ expose: false }, async (): Promise<void> => {
const due = await db.queryAll<{ id: number }>`
SELECT id FROM sessions
WHERE state = 'completed' AND billed_at IS NULL
AND ended_at <= now() - interval '5 minutes'`;
for (const s of due) {
await sessionCompleted.publish({ sessionId: s.id });
}
});
const _finalize = new CronJob("finalize-billing", {
title: "Price completed sessions after a meter grace period",
every: "1m",
endpoint: finalizeBilling,
});
const _ = new Subscription(sessionCompleted, "price-and-capture", {
handler: async ({ sessionId }) => {
const r = await db.queryRow<{ energy_wh: number }>`
SELECT max(register_wh) - min(register_wh) AS energy_wh FROM meter_values WHERE session_id = ${sessionId}`;
// Price with the tariff snapshot, store amount_cents, then capture the hold
// through your payment provider with an idempotency key of the session ID.
await db.exec`
UPDATE sessions SET energy_wh = ${r?.energy_wh ?? 0}, billed_at = now()
WHERE id = ${sessionId} AND billed_at IS NULL`;
},
retryPolicy: { maxRetries: 20 },
});
Repeated events are harmless: the insert ignores a second started, meter values dedupe on their key, and the conditional update makes a second ended a no-op. A cron job every minute publishes completed sessions whose ended_at is at least five minutes old and whose billed_at is still null, so a failed publish or a late meter reading in that window is picked up on the next run. The cron job is Encore platform managed and does not run locally or in preview environments, so call finalizeBilling directly when testing. Capturing with the session ID as the payment provider's idempotency key makes a retried subscriber safe, and failures land in the subscription's dead-letter queue after the retries run out. Driver app updates and OCPI pushes are further subscriptions on session-completed, each with its own retries.
A coding agent working in this repository can add a tariff component, such as a peak-hour energy price, as a code change and test it by replaying recorded charger logs locally before review.
Best fit: charge point operators and e-mobility teams that run their own session and billing logic and want it in their own AWS or GCP account.
It authorizes a driver at a charger, tracks the charging session from start to stop using events the charger sends over OCPP, stores meter values, prices the session with the tariff that applied when it started, and settles payment, usually by placing a hold at the start and capturing the final amount at the end. It also publishes session updates to the driver app and to roaming partners.
Keep the OCPP WebSocket layer in a small gateway that forwards normalized charger events to an Encore service. Declare a Postgres database for sessions and meter values and Pub/Sub topics for session events in TypeScript; subscribers price sessions and settle payments. On deploy to your own AWS account Encore provisions RDS, SNS and SQS, and an IAM role for the service.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.