Real-Time Fleet Data Platform Architecture
System DesignModel answerLast updated
Design a platform to monitor live telemetry from electric vehicles, covering data collection, ingestion, storage, APIs, and operational controls.
You're designing a monitoring platform for an electric vehicle company's internal operations team.
The platform needs to display live telemetry from their fleet—metrics like speed, cabin temperature, battery charge level, and location—as vehicles drive around. The operations team should be able to view current readings and historical trends for any vehicle.
Your design should address:
-
Vehicle data pipeline: How do vehicles capture and send telemetry to your backend? What protocols and data formats would you use?
-
Backend ingestion and storage: How does the system receive, validate, and store incoming data at scale? How do you ensure data quality and handle vehicles going offline?
-
Query and API layer: What APIs would you expose for internal tools? How would you efficiently retrieve the most recent speed reading for a given vehicle?
-
User interface: What would the monitoring dashboard show? How would you keep it responsive with live updates?
-
Operational controls: How would you implement a feature that stops a specific vehicle from sending data to any external systems? Consider both immediate enforcement and reliability when vehicles are offline.
-
AI-assisted development: How would you incorporate AI coding tools during implementation to speed up development while maintaining code quality, security, and long-term maintainability?
Make reasonable assumptions about fleet size and data volume, and state them clearly. Discuss trade-offs in your choices.
Hints
Hint 1
Start by estimating throughput: how many vehicles, how often does each send data, and what does that mean for messages per second and storage per day?
Hint 2
Consider the vehicle's connectivity reality—intermittent network, offline periods—and design for at-least-once delivery with deduplication.
Hint 3
For 'latest value' queries, think about a storage layer optimized for key-value lookups separate from your time-series store.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Real-Time Fleet Data Platform
1. Requirements and Scale Assumptions
Start by clarifying what you're building and the expected load.
Functional requirements:
- Vehicles transmit signals: speed, temperature, battery state, GPS coordinates
- Dashboard displays live readings per vehicle and the full fleet
- API returns current value for any metric on any vehicle
- Historical data queryable for trend analysis
- Ability to block data transmission from specific vehicles
Scale estimates:
- Fleet of 100,000 vehicles
- Each vehicle sends one message per second with ~20 data points
- Total: 100k messages/sec at ~300 bytes each = 30 MB/sec ingestion, roughly 2.6 TB/day
- Target latency: data visible in dashboard within 3-5 seconds of capture
- Retention: 90 days hot, then archive
Key constraints:
- Vehicles have unreliable connectivity and need to buffer data offline
- Privacy-sensitive data (location, driving patterns) requires authentication, authorization, and audit trails
- System must handle duplicates and out-of-order messages
2. Vehicle-Side Telemetry Collection
Data capture: The vehicle's telemetry unit reads sensor data from the internal vehicle network (CAN bus). It samples different signals at different rates—speed at 1 Hz, cabin temperature every 10 seconds, GPS every 2 seconds.
Message format: Batch samples into a compact binary format (Protocol Buffers work well). Each message includes:
- Vehicle identifier
- Sequence number (monotonic counter for deduplication)
- Device timestamp
- Array of signal name/value pairs
Transport protocol: Use MQTT over TLS with mutual authentication. Each vehicle gets a unique certificate installed during manufacturing. MQTT is ideal for intermittent connectivity: it's lightweight, supports QoS guarantees (at-least-once delivery), and handles reconnection automatically.
Offline handling: When connectivity drops, buffer messages in an on-device ring buffer with a size limit (say, 1 hour of data). On reconnect, drain the buffer oldest-first. This ensures critical data isn't lost during brief outages.
Remote configuration:
Vehicles subscribe to a configuration topic (e.g., config/vehicle/{id}) to receive commands like disabling telemetry or changing sample rates.
3. Backend Architecture
Vehicles (MQTT/TLS)
→ Load-balanced MQTT broker cluster (AWS IoT Core / HiveMQ)
→ Stream processor (Kafka topic: raw_telemetry, partitioned by vehicle_id)
→ Validation service
→ Valid → Kafka topic: validated_telemetry
├→ Current-state writer → Redis (latest values)
├→ Time-series writer → TimescaleDB (90-day queries)
├→ Archiver → S3 (long-term storage)
└→ External sharing service (policy-gated)
→ Invalid → Dead-letter queue
Why Kafka?
Kafka provides durable buffering between ingestion and processing. Partitioning by vehicle_id preserves per-vehicle ordering and enables horizontal scaling. If a downstream system slows, Kafka queues messages rather than dropping them.
Validation: Before storing, check:
- Schema version matches expected format
- Values are in valid ranges (speed 0-300 km/h, temperature -40 to 85°C)
- Timestamp is reasonable (not too far in the future)
- Certificate identity matches claimed
vehicle_id - No duplicate based on sequence number
Invalid messages go to a dead-letter queue for investigation.
Storage layers:
- Redis: Stores the single most recent value for each signal per vehicle. Optimized for sub-millisecond
GET /latestqueries. - TimescaleDB (or ClickHouse): Time-series database for range queries and downsampled aggregates (1-minute, 1-hour rollups) for charts.
- S3: Cold storage in columnar format (Parquet) for long-term analytics and compliance.
- PostgreSQL: Relational metadata—vehicle registry, user permissions, telemetry policies, audit logs.
4. APIs and Data Model
Redis schema (current state):
Key: vehicle:{id}:state
Hash: {
"speed": "65.2",
"speed_ts": "1735689600000",
"cabin_temp": "22.0",
"cabin_temp_ts": "1735689590000",
"last_seen": "1735689602000"
}
Time-series table:
telemetry (
vehicle_id TEXT,
signal TEXT,
timestamp TIMESTAMPTZ,
value DOUBLE PRECISION
)
Partitioned by time, indexed on (vehicle_id, signal, timestamp)
REST API (authenticated with OAuth2, role-based access):
| Endpoint | Purpose |
|---|---|
GET /vehicles | List fleet with filters (online/offline, low battery) |
GET /vehicles/{id}/current?signals=speed,cabin_temp | Latest values with timestamps |
GET /vehicles/{id}/history?signal=speed&start=&end=&interval=1m | Historical data, downsampled |
POST /vehicles/{id}/policy | Update transmission or sharing policy |
GET /vehicles/{id}/policy | Current policy and enforcement status |
WebSocket for live updates:
WS /stream?vehicles={id1},{id2} pushes updates as they arrive. Client-side throttling (max 2 updates/second) prevents UI thrashing.
5. Retrieving Latest Speed
GET /vehicles/{id}/current?signals=speed hits Redis with HGET vehicle:{id}:state speed speed_ts, returning in under 1ms.
Handling out-of-order data: Offline buffered messages can arrive after fresher data. The writer uses a Lua script to conditionally update: only overwrite if the incoming timestamp is newer than the stored one.
Response includes staleness:
{
"vehicle_id": "VH4829",
"speed": {
"value": 65.2,
"unit": "km/h",
"timestamp": "2025-01-01T12:00:00Z",
"stale": false
}
}
If Redis misses (cache cold start), fall back to querying TimescaleDB ORDER BY timestamp DESC LIMIT 1 and backfill Redis.
6. Disabling Telemetry for a Vehicle
Clarify the requirement: stop the vehicle from transmitting, or just block data from reaching external parties? A robust solution enforces both.
Layer 1: Policy database
POST /vehicles/{id}/policy with {"transmission_enabled": false} writes to PostgreSQL with a version number and audit entry (who, when, why). Requires elevated permissions.
Layer 2: Device enforcement
Publish the desired state to the vehicle's MQTT configuration topic (retained message): {"transmission_enabled": false, "version": 5}.
- If online, the vehicle stops transmitting immediately and acknowledges:
{"reported_version": 5}. - If offline, it receives the config on reconnect.
- Dashboard shows "pending" until reported version matches desired version.
Layer 3: Server-side enforcement
Device compliance isn't guaranteed (bugs, tampering). The ingestion pipeline checks the policy table for every message and drops data from vehicles with transmission_enabled: false, logging the violation.
Layer 4: Egress control
Even if data reaches internal systems, gate any external sharing with an additional external_sharing_enabled flag checked before forwarding to partners.
7. Frontend Dashboard
Fleet overview:
- Virtualized table (react-window) showing all vehicles
- Columns: ID, status (online/offline), last seen, current speed, battery level
- Filters: status, low battery alerts, geographic region
Vehicle detail page:
- Live gauges for key metrics with real-time updates via WebSocket
- Staleness indicator ("updated 2s ago")
- Time-series charts with date-range picker pulling from the history API
- Policy controls with confirmation dialog
Performance considerations:
- Throttle WebSocket updates to avoid overwhelming React re-renders
- Reconnect with exponential backoff on disconnect
- Graceful degradation to polling
/currentif WebSocket fails
8. Using AI Coding Assistants
Effective use during development:
- Scaffold boilerplate: Generate Kafka consumer skeletons, Redis client wrappers, API route handlers, and OpenAPI specs. These are tedious but low-risk.
- Data validation logic: Describe the rules ("speed between 0 and 300, reject timestamps more than 5 minutes in the future") and have the AI generate the validation functions. Review the edge cases.
- Test generation: AI can write unit tests for validation rules, mock Kafka producers, and API integration tests, increasing coverage quickly.
- Documentation: Generate inline comments, README sections, and runbook entries from code and architecture discussions.
Where to maintain control:
- Architecture decisions: AI can suggest patterns, but you decide on Kafka vs. Kinesis, Redis vs. Memcached, and how to partition data.
- Security-critical code: Review all authentication, authorization, and encryption code manually. Don't trust AI-generated crypto implementations.
- Data models and APIs: AI can draft schemas, but you validate that indexes, partitioning, and API contracts match long-term needs.
- Performance-sensitive paths: Profile and benchmark AI-generated query code. AI may produce working code that doesn't scale.
Workflow: Use AI for first-draft implementation and refactoring, but always review diffs, run tests, and verify that dependencies are current and well-maintained. Combine AI speed with human judgment on correctness, security, and maintainability.
Trade-offs Summary
- MQTT vs. HTTP: MQTT better handles intermittent connectivity; HTTP simpler to debug and firewall-friendly.
- Redis vs. in-memory cache: Redis provides persistence and replication; in-process cache is faster but lost on restart.
- TimescaleDB vs. ClickHouse: TimescaleDB easier for SQL users; ClickHouse faster for massive analytical queries.
- Device enforcement vs. server enforcement: Device enforcement reduces bandwidth; server enforcement is the security boundary.
This architecture balances real-time responsiveness, scalability, reliability, and operational control for a large-scale telemetry system.