Full-Stack in Practice: A Charging Station Admin Backend Built on Six Tables
This article walks through designing a charging station operations backend with only six database tables. It explains why abstraction—not a long skills checklist—is the real full-stack advantage, then covers core modeling principles: process-driven table design, storing money as integer cents, second-level timestamps, and readable status strings. Each table is broken down (users, stations, chargers, sessions, reservations, incidents), along with transaction-based settlement, idempotent updates, reservation conflict prevention, indexing strategy, and lessons learned from real mistakes. Readers get a stable domain model that serves UI, APIs, and data consistency at once.
1. Define the Problem First: The Full-Stack “Superpower” Is Abstraction
Many people treat full-stack development as “I can build pages on the frontend and endpoints on the backend.” That is a skills checklist, not the underlying capability. What actually makes a full-stack developer look like they have a superpower is the ability to extract a stable domain model quickly when requirements are vague, and to make that single model serve UI interactions, API contracts, and data consistency at the same time. Once the data model is stable, frontend forms, backend endpoints, permission checks, and reports all grow naturally around it. If the model keeps shifting, every layer after it has to be reworked repeatedly.
Take a charging station operations backend as an example. The business sounds sprawling: finding stations on a map, charger status, billing, reservations, fault alerts. But if you walk through a real usage path, the core is only three kinds of things:
- People: car owners, station administrators, super administrators;
- Points: charging stations, chargers;
- Events: charging sessions, payments, reservations, faults.
Once these three entity groups are drawn clearly, six tables are enough to carry every core flow in the first version. This is not cutting corners; it is putting the complexity where it is actually needed.
2. Overall Modeling Principles: Make It Run First, Make It Easy to Change Second
1. Let the Process Drive the Table Structure
Beginners tend to create tables from nouns: see “map” and build a map table, see “message” and build a message table. A more reliable approach is to build tables from processes. A charging session goes from QR scan to settlement—which states does it pass through, and which facts must be kept as a record? Those facts are what need tables.
2. Store All Money as Integer Cents
One of the most common traps in database design is using floating point to store money. In this design, every amount field is an integer in cents. For example, a balance of 12345 means 123.45. The presentation layer divides by 100 and formats it. This avoids precision errors and makes aggregate reporting more reliable.
3. Use Second-Level Timestamps Everywhere
Use integer second-level timestamps consistently. The benefits are no ambiguity across time zones, efficient range queries, and simple frontend handling. Convert to local time only when displaying.
4. Use Short Strings for Status, Not Magic Numbers
Status fields use readable short strings, with comments or constants constraining the allowed values. The maintenance benefit of readability far outweighs the few extra bytes.
3. Breaking Down the Six Tables
Table 1: Users
This table carries “people.” The key design decision is a single role field that distinguishes owners from administrators, instead of a separate table per role. Role differences show up mainly in permissions and visible data scope, not in the data structure itself.
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT NOT NULL,phone TEXT UNIQUE NOT NULL,password_hash TEXT NOT NULL,role TEXT NOT NULL DEFAULT 'customer', -- customer / adminbalance INTEGER NOT NULL DEFAULT 0, -- unit: centsstatus TEXT NOT NULL DEFAULT 'active', -- active / disabledcreated_at INTEGER NOT NULL DEFAULT (strftime('%s','now')));
Key points: the unique phone constraint serves as the login identifier; only the password hash is stored; the balance is an integer in cents; the status field supports soft disabling, so historical data does not break because of deletion.
Table 2: Stations
A station carries geographic and commercial information. Suggested fields include name, latitude and longitude, address, business hours, service fee per unit (integer cents per kWh), status, and creation time. Latitude and longitude can be floating point, but you must build a plain index combination that is friendly to spatial queries. A common approach is a (lat, lng) composite index: filter roughly by latitude first, then match precisely, avoiding a full table scan.
Table 3: Chargers
A charger belongs to a station, so the station_id foreign key is required. Core fields are the charger code, power limit, connector type, current status (idle / occupied / offline / fault), and firmware version. The design point here: charger status is a “real-time state” that updates frequently and must be kept separate from a “fact state” like a session. Real-time state can be overwritten; fact state is append-only and never modified.
Table 4: Sessions
This is the hub of the whole model. One charging session is one row, with fields for user, charger, start time, end time, starting energy, ending energy, energy consumed, electricity fee, service fee, total amount, and status. A good status abstraction is initiated → charging → completed, with aborted as the exception branch.
Settlement logic must live inside a transaction: write the end time and usage, calculate fees, deduct or record the balance, and set the charger back to idle. If any step fails, roll back everything. Sketch:
BEGIN;UPDATE sessions SET end_at=?, kwh=?, total_fee=?, status='completed' WHERE id=? AND status='charging';UPDATE chargers SET status='idle' WHERE id=(SELECT charger_id FROM sessions WHERE id=?);COMMIT;
The conditional update with WHERE status='charging' gives you idempotency naturally: a repeated submission will not settle twice.
Table 5: Reservations
A reservation is essentially “occupying a time interval.” Fields include user, charger, reservation start and end time, status, and the associated session. Preventing re-entry is the hard part. Two lines of defense are recommended: first, the application layer queries for overlapping time records inside a transaction; second, the database enforces a unique index on (charger_id, start_at), leaving concurrency to the constraint as a backstop. Reservations that time out without starting are batch-marked invalid by a scheduled job, which also releases the hold.
Table 6: Incidents
An alert cannot just be written to a log; it has to form a closed loop. Fields include charger, session (nullable), fault type, description, severity level, status (open / processing / resolved), handler, and creation and resolution times. Faults are many-to-one with chargers, and only loosely associated with users through the handler field, avoiding another people table just for “who handled it.”
4. Table Relationships and Indexing Strategy
The relationships fit in one sentence: users initiate sessions and reservations, sessions happen on chargers, chargers belong to stations, and faults attach to chargers with an optional link to a session. The whole thing is a tree rooted at stations, plus the horizontal thread of users.
Index suggestions:
sessions(charger_id, start_at): supports charger-dimension history queries;sessions(user_id, start_at DESC): supports “my charging records”;reservations(charger_id, start_at)unique: prevents duplicate reservations;incidents(status, created_at): supports the pending-work-order list.
The principle: index only high-frequency queries that carry filter conditions, and keep indexes minimal on real-time status tables that are write-heavy and read-light.
5. Pitfalls I Hit (Honest Regrets)
- I first split fees into several detail tables, so one settlement spanned four tables, the transaction grew long, and the failure rate rose. After merging them into the session table, the complexity dropped sharply.
- I stored amounts as floating point and reconciliation was always off by a few cents, which took ages to track down. Switching to integer cents made the problem disappear.
- I put the charger’s real-time status into the session table, so the status was overwritten repeatedly and history could not be traced. Real-time state and fact state must be separated.
- Reservations relied only on application-layer duplicate checks, and load testing still produced duplicate reservations. A unique constraint ended up as the backstop.
- I ignored migrations and hand-wrote scripts when changing fields, which caused production errors. I later settled on a “schema script plus versioned migrations” process, so every change can be rolled back.
6. Practical Advice and Extensions
For a small or mid-sized backend, an embedded database with a synchronous driver is entirely sufficient, and it saves the deployment and operations cost of a separate database service. When concurrency and data volume grow, you can migrate smoothly to a centralized database with no major schema changes. If you later add map display, message notifications, or monitoring alerts, connect them as general-purpose capability categories—object storage for images, a message queue for asynchronous notifications, logging and monitoring services for observability—rather than stuffing them into the main database.
The full-stack “superpower” is ultimately restrained design: using the fewest tables to describe the most complete business, using constraints and transactions to hold consistency, and using versioned migrations to stay changeable. Six tables are not the finish line; they are the starting point that gives every later extension a solid foundation.
