System Architecture
This section provides a comprehensive overview of how the tracking backend is structured and how its components interact internally.Project Structure
Core Design Patterns
DB-First Reads with Background Sync
The system follows a DB-first read pattern to ensure immediate API responses:- API requests read directly from PostgreSQL for immediate responses
- Background pollers continuously sync data from external APIs
- Cache layer reduces redundant external API calls
- Staleness tracking via
updated_attimestamps
Dynamic Polling Strategy
Polling intervals adapt based on SSE client activity:| State | Interval | Condition |
|---|---|---|
| Active | 5-10 seconds | SSE clients connected |
| Idle | 60 seconds | No active SSE clients |
location_stream.py via a client counter that triggers faster polling when client_count > 0.
Token Bucket Rate Limiting
External API calls use a proactive token bucket algorithm:Data Flow Diagrams
Location Data Flow
Movement Data Flow
Database Models
Key Tables and Relationships
| Table | Purpose | Key Fields |
|---|---|---|
movements | Load/shipment records | id, order_id, status, driver_id |
drivers | Driver profiles & HOS | id, name, hos_status, location |
tractors | Vehicle data & locations | id, unit_number, latitude, longitude |
trailers | Trailer tracking | id, unit_number, latitude, longitude |
orders | Order headers | id, customer, movement_id |
stops | Pickup/delivery stops | id, order_id, type, eta |
Staleness Tracking
Every table includes:updated_at- Last database update timestampsynced_at- Last external API sync timestamp (where applicable)
Service Layer Details
Terminal API Integration (terminal_api.py)
Handles communication with ELD providers:
- Motive: OAuth2 authentication, REST API
- Samsara: API key authentication, REST API
- Geotab: Session-based authentication, MyGeotab SDK
- Connection pooling
- Automatic retry with exponential backoff
- Error normalization to common schema
Cache Service (cache_service.py)
In-memory caching with TTL:
- Location data: 30 seconds
- HOS data: 60 seconds
- Driver profiles: 300 seconds
Gemini Service (gemini_service.py)
AI chat uses function calling with these tools:
| Tool | Purpose |
|---|---|
get_driver_location | Fetch driver’s current position |
get_movement_status | Check load status |
get_eta | Calculate arrival time |
search_drivers | Find drivers by name/ID |
Lifespan Management
FastAPI’s lifespan context manages background services:Environment Configuration
Key settings fromconfig.py:
| Variable | Purpose |
|---|---|
DATABASE_URL | PostgreSQL connection string |
TERMINAL_API_KEY | ELD provider API key |
MCLEOD_API_URL | TMS integration endpoint |
MAPBOX_TOKEN | ETA calculation service |
GEMINI_API_KEY | AI chat functionality |
POLLING_INTERVAL | Background sync frequency |

