How huybaoo1/distributed-system-api-gateway-dang-phan-bao-huy works
1. Overall shape
This repo is not a single app but a small distributed testbed for an API gateway. The main runtime path is: client traffic goes to a Spring Boot gateway, the gateway rate-limits and measures latency, then proxies allowed requests to a mock backend. Redis is the shared state store for the distributed rate limiters.
2. Gateway service boundary
api-gateway is the core component. It exposes /api/v1/** as the public request surface and has internal endpoints for metrics and system inspection. The gateway is also where the architecture variants live: different rate-limiting strategies, different Redis fault policies, and the latency headers used for experiments.
3. Request flow through the gateway
Incoming requests first pass through a rate-limiting filter, then the gateway forwards them to the backend service. On the response path, it adds timing and quota headers such as rate-limit latency, backend latency, total gateway latency, remaining quota, reset time, and Retry-After for rejections. This makes the gateway both a proxy and a measurement instrument.
4. Rate limiting subsystem
The repo contains four limiter modes:
- redis-sliding-window
- redis-fixed-window
- redis-token-bucket
- in-memory
The Redis-backed strategies use Redis as the authoritative state store and differ only in how quota state is modeled. The in-memory mode is local to one gateway instance and serves as a baseline or fallback comparison point.
5. Redis fault handling boundary
Redis is treated as a potentially failing dependency. The gateway supports three policies when Redis is unreachable:
- fail-closed
- fail-open
- local-fallback
This is an important architectural boundary because availability and correctness trade off differently depending on policy. The “local fallback” path shifts decision-making from distributed state to per-instance state during failure.
6. Latency and observability path
The gateway has dedicated controllers and services for reporting internal latency snapshots and formatting metrics. The repository is built to separate client-observed latency from gateway processing, backend delay, and rate-limiter overhead. That separation is central to the experiment design and is exposed through headers plus internal report endpoints.
7. Backend simulation
mock-backend-service/mock-backend-service is a minimal Spring Boot backend that simulates downstream latency through a delayMs parameter. It exists to isolate gateway behavior from real application complexity. This backend is the target of the gateway proxy and is the source of controlled backend delay in experiments.
8. Runtime topology and deployment
The repo includes Dockerfiles and docker-compose.yml for running the full stack locally: gateway(s), mock backend, Redis, and Redis Commander. There is also a scaled setup using Nginx as a load balancer in docker-compose.scaled.yml and nginx/gateway-scaled.conf, which models a multi-instance gateway deployment behind a shared entrypoint.
9. Experiment and analysis tooling
The Python scripts are an external experiment harness rather than part of the gateway runtime. They drive benchmark traffic, generate scenario matrices, inject Redis failures, and produce reports/plots. The reports/ directory stores manifests and trial outputs, while plot_latency_report.py and the dashboard consume those artifacts for analysis.
10. Test and verification structure
The gateway has unit tests for the controller, filter, and service logic, plus Redis integration tests using Testcontainers. The backend has a basic Spring context test. This splits verification into fast local behavior checks and environment-backed checks that validate Redis-dependent strategies.
11. User-facing analysis UI
ui/latency-dashboard is a static dashboard that reads experiment CSV/manifest outputs and visualizes latency comparisons. It is not part of the request path; it is a post-processing view for the artifact pipeline.
12. Architecture diagram cues
A correct diagram should show:
- clients hitting one of several gateway entrypoints
- gateway internals split into request filtering, rate-limit decisioning, proxying, and metrics
- Redis as a shared distributed dependency for most strategies
- mock backend as the downstream target
- experiment scripts and report artifacts as an offline analysis pipeline
- optional Nginx/load-balanced gateway deployment for scale-out scenarios
Main entry points: ApiGatewayApplication.java API Gateway · RateLimiterService.java Limiter Modes · MockBackendServiceApplication.java Mock Backend · run_latency_experiments.py Experiment Scripts
Components 23
Runtime stack
Gateway request path, downstream backend, and shared Redis state.
- Clients · External callers hitting the gateway APIs.
- API Gateway · Core proxy, rate-limiter, and latency measurement service.
api-gateway/src/main/java/com/example/apigateway/ApiGatewayApplication.java - API Surface · Public API and internal inspection endpoints exposed by the gateway.
api-gateway/src/main/java/com/example/apigateway/controller/ApiGatewayController.java - Latency API · Internal endpoints for latency snapshots and metrics reporting.
api-gateway/src/main/java/com/example/apigateway/controller/LatencyMetricsController.java - System API · Exposes system properties and runtime inspection data.
api-gateway/src/main/java/com/example/apigateway/controller/SystemPropertiesController.java - Rate Filter · First request gate that applies quota decisions before proxying.
api-gateway/src/main/java/com/example/apigateway/filter/RateLimitingFilter.java - Limiter Modes · Pluggable limiters for Redis-backed and local in-memory quota enforcement.
api-gateway/src/main/java/com/example/apigateway/service/RateLimiterService.java - Redis Windows · Sliding-window and fixed-window quota strategies backed by Redis state.
api-gateway/src/main/java/com/example/apigateway/service/RedisSlidingWindowRateLimiterService.java - Token Bucket · Redis-backed token bucket implementation for quota tracking.
api-gateway/src/main/java/com/example/apigateway/service/RedisTokenBucketRateLimiterService.java - Local Fallback · In-memory or local-window fallback path used when Redis is unavailable.
api-gateway/src/main/java/com/example/apigateway/service/InMemoryRateLimiterService.java - Redis Policy · Implements fail-open, fail-closed, and local-fallback behavior for Redis outages.
api-gateway/src/main/java/com/example/apigateway/service/RedisFailureHandler.java - Latency Metrics · Collects gateway/backend timing and formats response headers.
api-gateway/src/main/java/com/example/apigateway/service/LatencyMetricsService.java - Header Formatter · Builds latency and quota headers for client-visible responses.
api-gateway/src/main/java/com/example/apigateway/http/GatewayHeaders.java - Backend Proxy · Forwards allowed requests to the backend and tracks downstream failures.
api-gateway/src/main/java/com/example/apigateway/service/BackendCircuitBreaker.java - Mock Backend · Minimal downstream service that injects controlled latency via delayMs.
mock-backend-service/mock-backend-service/src/main/java/com/example/mock_backend_service/MockBackendServiceApplication.java - Redis · Authoritative state for distributed rate limiters and fault scenarios.
Experiment pipeline
Scripts, reports, and dashboard used to run and analyze latency studies.
- Experiment Scripts · Python tools that generate traffic, inject faults, and compare strategies.
run_latency_experiments.py - Reports · Manifests, CSVs, and trial outputs consumed by the dashboard and plots.
reports/dashboard-live/manifest.json - Latency Dashboard · Browser UI that visualizes latency comparison artifacts.
ui/latency-dashboard/index.html
Deployment setup
Local compose and scaled Nginx-based topology.
- Compose Stack · Docker Compose setup for gateway, backend, Redis, and Redis Commander.
docker-compose.yml - Scaled Stack · Nginx-fronted gateway deployment for load-balanced scenarios.
docker-compose.scaled.yml
Verification
Tests that validate gateway behavior and Redis-backed strategies.
- Gateway Tests · Controller, filter, service, and Testcontainers coverage for the gateway.
api-gateway/src/test/java/com/example/apigateway/controller/ApiGatewayControllerTest.java - Backend Tests · Basic application context verification for the mock backend.
mock-backend-service/mock-backend-service/src/test/java/com/example/mock_backend_service/MockBackendServiceApplicationTests.java
Connections 27
- Clients → API Gateway: HTTP requests · Client traffic enters the gateway public surface.
- API Gateway → API Surface: routes to · Public and internal endpoints are handled by gateway controllers.
- API Gateway → Rate Filter: filters through · Incoming requests are checked before proxying.
- Rate Filter → Limiter Modes: delegates quota · The filter selects a limiter strategy for the request.
- Limiter Modes → Redis Windows: redis mode · Sliding-window and fixed-window strategies use Redis state.
- Limiter Modes → Token Bucket: redis mode · Token bucket strategy uses Redis state.
- Limiter Modes → Local Fallback: local mode · In-memory or fallback quota enforcement stays local to the instance.
- Limiter Modes → Redis Policy: policy hook · Redis-unavailable behavior is determined by the failure policy.
- Redis Windows → Redis: reads/writes · Distributed quota state is stored in Redis.
- Token Bucket → Redis: reads/writes · Token state is stored in Redis.
- Redis Policy → Redis: monitors · Failure handling reacts to Redis connectivity and availability.
- API Gateway → Latency Metrics: measures · Gateway processing and backend timings are captured.
- Latency Metrics → Header Formatter: formats headers · Timing and quota data are rendered into response metadata.
- API Gateway → Backend Proxy: proxies to · Allowed requests are sent to the downstream service.
- Backend Proxy → Mock Backend: downstream calls · The gateway targets the mock backend for controlled delay.
- Mock Backend → Redis: independent of · Backend simulation does not depend on Redis.
- Compose Stack → API Gateway: runs · Local compose starts the gateway service.
- Compose Stack → Mock Backend: runs · Local compose starts the mock backend service.
- Compose Stack → Redis: runs · Local compose includes Redis as shared state.
- Scaled Stack → API Gateway: scales · The scaled deployment runs multiple gateway instances.
- Scaled Stack → Redis: shares state · All gateway instances use the same Redis dependency.
- Experiment Scripts → API Gateway: drives · Benchmark scripts generate traffic against the gateway.
- Experiment Scripts → Mock Backend: controls delay · Scenarios vary backend latency to isolate gateway behavior.
- Experiment Scripts → Reports: writes · Runs produce manifests, trial JSON, and CSV summaries.
- Reports → Latency Dashboard: feeds · The dashboard reads artifact files for visualization.
- Gateway Tests → API Gateway: verifies · Gateway behavior is covered by unit and integration tests.
- Backend Tests → Mock Backend: verifies · Backend application startup is checked by tests.