Codeground AI
EditorWorkspacesInterviews Meet New Daily Challenges
Data & format
  • JSON DiffCompare two JSON blobs side by side
  • Diff & PatchGenerate unified patches from text/code
  • JSON FormatterPretty-print and validate JSON
  • SQL FormatterFormat SQL and explain with AI
  • JSON ↔ CSVConvert tabular data both ways
  • Base64 CodecEncode and decode Base64
  • Log ParserPretty-print logs and highlight severity
Security & web
  • JWT DebuggerDecode and verify JSON Web Tokens
  • ENV LinterLint .env files and redact values
  • Password GeneratorStrong, configurable passwords
  • UUID GeneratorGenerate UUID v1/v4 in bulk
  • Regex TesterTest patterns in real time
Generators & utilities
  • Epoch ConverterConvert between Unix and dates
  • Meeting PlannerMatrix of slots across timezones
  • Date MathAdd duration with timezone awareness
  • Cron BuilderValidate cron and preview next runs
  • QR GeneratorMake scannable QR codes
  • Color PickerPick & convert colors
  • Lucky Draw WheelSpin-the-wheel utility
Network & creative
  • Speed TestMeasure network throughput
  • Diagram StudioFlowcharts & architecture diagrams
  • Canvas DrawingA scratchpad for sketches
  • Turtle GameCoding game for kids
See everything Codeground AI offers
Reads
Sign In Sign Up
EditorWorkspacesInterviewsMeetDaily ChallengesReads
Tools
JSON DiffDiff & PatchJSON FormatterSQL FormatterJSON ↔ CSVBase64 CodecLog ParserJWT DebuggerENV LinterPassword GeneratorUUID GeneratorRegex TesterEpoch ConverterMeeting PlannerDate MathCron BuilderQR GeneratorColor PickerLucky Draw WheelSpeed TestDiagram StudioCanvas DrawingTurtle Game

Sign InSign Up

Notifications 0

A Complete System Design Doc Of A Traffic Signal System

Ashutosh Singh - May 18, 2025


Introduction

Designing a Traffic Signal System may seem like a straightforward task at first glance, but it's a great problem for testing a candidate’s understanding of real-time systems, concurrency, hardware-software interaction, and fault tolerance.

This system is commonly asked in low-level or high-level design rounds at companies like Google, Uber, or Amazon. In this post, let’s walk through how to design such a system using a structured design document format.

Use Case & Requirements

Functional Requirements

  1. Each traffic signal controls four directions (North, South, East, West).
  2. Traffic lights can be: Red, Yellow, or Green.
  3. Only one direction can have Green at any time to avoid collisions.
  4. The signal should change every n seconds (e.g., 60 seconds Green, 5 seconds Yellow).
  5. It should support manual override for emergencies.
  6. The system should be able to handle multiple intersections.

Non-Functional Requirements

  • High availability.
  • Real-time responsiveness.
  • Fault tolerance for sensor/hardware failure.
  • Scalable to support many intersections.
  • Optional: Smart control based on traffic density.

High-Level Design

Components

  1. Traffic Light Controller
  2. Decides the current state (Green, Yellow, Red).
  3. Handles time transitions and overrides.
  4. Intersection Manager
  5. Manages multiple traffic lights at one intersection.
  6. Ensures only one direction is green at any time.
  7. Central Traffic Control System (optional for scaling)
  8. Monitors and controls multiple intersections.
  9. Sends commands for manual override or emergency handling.
  10. Sensors (Optional for Smart Traffic)
  11. Detect vehicles, pedestrians, and traffic density.
  12. Helps optimize signal timing.
  13. Client Interface
  14. Admin dashboard for monitoring.
  15. Emergency services UI for override.

Low-Level Design

Class Design (Object-Oriented)

enum LightColor {
    RED, YELLOW, GREEN
}

class TrafficLight {
    private LightColor color;
    public void setColor(LightColor color);
    public LightColor getColor();
}

class TrafficDirection {
    private String name;
    private TrafficLight light;
}

class Intersection {
    private List<TrafficDirection> directions;
    private int currentIndex = 0;

    public void startCycle();
    private void switchToNextDirection();
}

class TrafficSignalController {
    private List<Intersection> intersections;
    public void run();
}

State Machine Diagram

Each direction follows a state transition:

RED → GREEN → YELLOW → RED

Each state is maintained for a fixed duration using a timer. The Intersection manages transitions between directions in a round-robin fashion.

Timing and Concurrency

Threading Model

Each intersection runs a separate thread or scheduler to manage its signals. You can use a ScheduledExecutorService in Java or setInterval in Node.js.

js
CopyEdit
setInterval(() => {
  intersection.switchToNextDirection();
}, TIME_INTERVAL);

To avoid race conditions, only one direction can be GREEN at a time. Use mutexes/locks if concurrency is involved.

Data Storage (Optional – But Valuable in Real-World Systems)

In a basic traffic signal system, there’s no strict need for persistent storage—everything can be handled in-memory using timers and state machines. However, real-world deployments benefit significantly from storing key data to enable monitoring, analytics, and fault recovery.

Here’s what you might store and why:

1. State Logs for Debugging

What:

Store every state change of each traffic light (e.g., from Red → Green → Yellow) along with a timestamp and direction.

Why:

  • It helps reconstruct events during a failure or traffic incident.
  • Useful for debugging bugs in state transitions or timers.
  • Helps prove compliance with signal timing regulations (especially in smart cities).

Example Entry (MongoDB):

{
  "intersectionId": "INT-42",
  "direction": "North",
  "previousState": "RED",
  "currentState": "GREEN",
  "changedAt": "2025-05-18T08:32:00Z"
}

2. Override Events

What:

Store all manual or automated overrides — e.g., when an admin changes the state to allow emergency vehicles or maintenance work.

Why:

  • Critical for auditing and accountability.
  • Allows the system to restore normal operations after an override.
  • Enables monitoring who changed what and why.

Example Entry (SQL Table):

event_idintersection_idtriggered_byreasonoverride_statetimestamp1012INT-42admin_user_1AmbulanceNORTH → GREEN2025-05-18 08:32:00

3. Traffic Density History

What:

Store sensor data such as vehicle count per lane, average wait times, and peak hours.

Why:

  • Enables smart scheduling based on real traffic flow.
  • Supports ML models to dynamically optimize signal timings.
  • Useful for city planning (e.g., widening roads, rerouting).

Example Entry (MongoDB or Time-Series DB):

{
  "intersectionId": "INT-42",
  "timestamp": "2025-05-18T08:30:00Z",
  "northLane": {
    "vehicleCount": 12,
    "avgWaitTimeSec": 45
  },
  "southLane": {
    "vehicleCount": 5,
    "avgWaitTimeSec": 20
  }
}

Which Database to Use?

  • Use SQL (e.g., PostgreSQL, MySQL) if:
  • You need structured data with relationships.
  • You want strong ACID guarantees and transactional consistency.
  • Use NoSQL (e.g., MongoDB) if:
  • You need flexible schemas (e.g., logging data with variable shape).
  • You prioritize horizontal scalability.
  • You want to store log-like documents or time-based sensor data.

External Interfaces

  • Sensor API: To read traffic density.
  • Admin Panel API: For manual control.
  • Notification Service: To send alerts if hardware fails.

Fault Tolerance & Edge Cases

  • If a light malfunctions, → fallback to flashing Yellow.
  • If communication with the central controller fails, → the intersection should run autonomously.
  • Ensure time drift doesn’t desync multiple intersections.

Scaling the System

For a city-wide implementation:

  • Deploy multiple controllers per region.
  • Use message queues (e.g., Kafka) for communication between intersections and central control.
  • Store real-time metrics in a Time-Series DB like Prometheus.

Smart Enhancements

  1. Adaptive Traffic Lights
  2. Use sensors to vary green light time based on traffic.
  3. Emergency Vehicle Detection
  4. Override lights when an ambulance/police is detected.
  5. Pedestrian Crossing
  6. Add request-based crosswalk timers.

Conclusion

Designing a Traffic Signal System touches upon multiple key areas:

  • Real-time scheduling
  • Concurrency & synchronization
  • Hardware-software interaction
  • Fault tolerance
  • Scalable architecture

This is a great interview problem to showcase your ability to translate real-world scenarios into software design. The key is to start simple, then iterate with improvements like smart sensors or crosswalks. I hope you like it.

Adios, until next time 👋🏻!


Codeground AI

The browser is the only IDE you need. Cloud workspaces, 15+ language runtimes, secure interview tooling and a polished developer toolbox — all in one tab.

Languages

  • Node.js
  • Python
  • Java
  • C++
  • Go
  • Rust
  • TypeScript
  • Web (HTML/CSS/JS)
  • Shell / Bash

Databases

  • MongoDB
  • PostgreSQL
  • MySQL
  • Redis
  • ClickHouse

Tools

  • JSON Diff
  • Diff & Patch
  • JSON Formatter
  • JSON ↔ CSV
  • JWT Debugger
  • Base64 Codec
  • Regex Tester
  • Epoch Converter
  • Cron Builder
  • Meeting Planner
  • SQL Formatter
  • ENV Linter
  • Date Math
  • Log Parser
  • QR Generator
  • UUID Generator
  • Color Picker
  • Password Generator
  • Speed Test
  • Diagram Studio
  • Canvas Drawing
  • Lucky Draw Wheel

Platform

  • Daily Challenges
  • Interviews
  • Reads
  • Turtle (Kids)

Company

  • About Us
  • Privacy Policy
  • Sitemap
  • Contact

© 2026 Codeground AI. Built for developers who want to ship.

About·Privacy·Sitemap·[email protected]