The user wants a "microservice architecture simulator." This is a broad request. I need to figure out what specific aspects of microservices this simulator should cover to make it useful and educational, while remaining within the scope of a single code generation response.
Scope & Features:
- Nodes/Services: The core entities. They should have names, statuses (UP, DOWN), and possibly dependencies.
- Communication: Services talk to each other. I should simulate synchronous (HTTP/REST-like) and maybe asynchronous (Message Queue) patterns, though synchronous is easier to visualize in a simple simulation.
- Latency/Failures: To make it a "simulator," things need to go wrong. I need to introduce network latency, service crashes, and high load.
- Observability: It's useless without seeing what happens. I need logs and a visual representation. A terminal-based UI (TUI) is best for a standalone script (no HTML/JS dependencies if possible, or a simple Tkinter/HTML GUI). Let's stick to a robust Python script with a visual component (maybe using
rich or just structured console output) to keep it self-contained. Actually, a web-based visualization (HTML/JS) connecting to a Python backend is too complex for a single file response. A Python script using asyncio to simulate concurrency and a simple print-based dashboard or a library like rich would be excellent. Let's assume standard libraries + rich (if available) or just plain standard library for maximum portability.
- Decision: I will use standard Python libraries +
networkx (for logic) and matplotlib (for a visual graph) OR just a standard library async simulation with text-based output.
- Better approach for a "cool" result: A Python script using
asyncio to run services as concurrent tasks. I will use the rich library if the user has it, but since I can't guarantee external libraries, I'll write a version that can use rich for a pretty UI but falls back to standard prints, or just stick to a robust logic engine that the user can interact with via code.
- Wait, the prompt is "Create a microservice architecture simulator". A graphical output is usually expected. Let's provide a Python solution that sets up a network of services, simulates traffic, failures, and prints logs.
Architecture of the Simulator:
- Service Class: Represents a microservice.
- Properties: Name, dependencies, health (circuit breaker state), response time.
- Methods:
receive_request, process, send_request.
- Network/LB: A way to route requests.
- Chaos Monkey: A background task that randomly kills services or adds latency.
- Generator: Generates user traffic.
Implementation Plan (Python):
- Use
asyncio for non-blocking simulation of network calls.
- Service: An
async function that listens for "requests" (maybe via an asyncio.Queue).
- Gateway: Entry point.
- Simulation: Run for X seconds, logging what happens.
Refining the Code Structure:
Let's build a modular system.
Service: Holds a queue. Runs a loop processing items. Calls other services.
Request: A data class tracking the path and latency.
Simulator: The orchestrator.
Let's add a specific scenario: An E-commerce order flow.
Services: Frontend, Cart, Inventory, Payment, Email.
Frontend -> Cart -> Inventory -> Payment -> Email.
Chaos Engineering features:
- Random crashes.
- High latency spikes.
Output:
Since I cannot display a real-time GUI easily in a text block, I will generate a log trace and a summary report. I will structure the code so it's easy to extend.
Let's actually try to make a simple text-based "UI" that updates in the console using cursor escape codes or just a stream of logs. A stream of logs with timestamps and colors (using ANSI codes) is best for a single-file copy-paste solution.
Step-by-Step Code Construction:
- Imports:
asyncio, random, dataclasses, time.
- Helper: Color printing.
- Data Structures:
Request, ServiceConfig.
- The Service Class:
__init__: name, dependencies.
start(): The async loop.
process_request(): Logic to sleep (simulate work) and call dependencies.
- Circuit Breaker: If a dependency fails too often, stop calling it.
- The Orchestrator:
- Sets up services.
- Injects traffic.
- Injects failures.
- Visualization: A simple ASCII art status updater would be cool, but might be too complex to code reliably cross-platform in a short script. Let's stick to detailed Logging.
Self-Correction/Improvement:
Just logs are boring. Let's simulate a "Chaos Test".
- Run normal traffic.
- Kill a backend service.
- Watch the Circuit Breakers trip.
- Revive the service.
- Watch the Circuit Breakers reset (Half-Open -> Closed).
Let's refine the "Circuit Breaker" implementation. It needs states: CLOSED (normal), OPEN (failing fast), HALF_OPEN (testing).
Final Code Structure:
Service: Has a name, list of downstream dependencies, and a circuit_breaker map for each dependency.
run_simulation: Main entry point.
Let's write the code. I'll provide a comprehensive Python script.
Note: I will write this to be runnable as is (standard library only).
Logic Flow for the Simulator:
- Define
Service class.
- It needs a
request_queue.
- It needs a
latency profile.
- It needs
circuit_breakers for dependencies.
- Define
CircuitBreaker class.
- Track failures. Open if threshold exceeded. Allow 1 test request after timeout.
- Define
LoadGenerator: Pushes requests to Gateway.
- Define
ChaosMonkey: Periodically toggles the "health" of a service.
- Main loop:
asyncio.gather everything.
Let's add an "Architecture" visual in the comments at the top.
Drafting the Response:
I will provide a complete Python script.
I will explain how to run it.
I will explain the concepts demonstrated (Latency, Circuit Breakers, Cascading Failures).
Detailed Code Logic:
RequestContext: Tracks ID, start time, path.
Service:
state: HEALTHY, UNHEALTHY.
handle_request:
- If UNHEALTHY: raise error immediately.
- If HEALTHY: sleep(random_latency).
- For each dependency:
- Check Circuit Breaker.
- If Open: raise CircuitOpenError.
- Try: send request.
- Catch Error: record failure in CB, raise error upstream.
- Success: record success in CB.
CircuitBreaker:
state: CLOSED, OPEN, HALF_OPEN.
failure_count: int.
last_failure_time: float.
threshold: 3.
timeout: 5s.
This looks solid. It covers the prompt "microservice architecture simulator" by simulating behavior, not just structure.
(Self-Correction): Should I include a GUI? No, a robust CLI simulator is better for code understanding and modification.
Let's write the Python code. I'll use asyncio because it's the standard way to handle IO-bound concurrency in Python, fitting for network simulation.
Code Elements:
ANSI colors for readability.
asyncio.sleep for latency.
try/except blocks for failure propagation.
Let's get to it.
This is a complete, functional Microservice Architecture Simulator written in Python.
It simulates a distributed system with the following real-world features:
- Services: Independent nodes (Frontend, Orders, Inventory, Payment).
- Network Latency: Random delays to simulate real network conditions.
- Failure Injection: A "Chaos Monkey" that randomly crashes services.
- Circuit Breakers: Prevents cascading failures by stopping calls to dead services.
- Asynchronous Processing: Uses Python's
asyncio to handle thousands of requests concurrently.
How to run it
Save the code below into a file named simulator.py and run it with Python 3.7+.
python simulator.py
The Code
import asyncio
import random
import time
from dataclasses import dataclass, field
from enum import Enum, auto
from typing import List, Dict, Optional
# --- Configuration ---
SIMULATION_TICK = 0.1 # Speed of the simulation loop
REQUEST_INTERVAL = 0.5 # How often new users send requests
CHAOS_INTERVAL = 5.0 # How often the 'Chaos Monkey' tries to break things
# --- Enums & Data Classes ---
class ServiceStatus(Enum):
HEALTHY = auto()
STRUGGLING = auto() # High latency
DOWN = auto()
class CircuitState(Enum):
CLOSED = auto() # Flow is normal
OPEN = auto() # Failing fast, blocking traffic
HALF_OPEN = auto() # Testing if service is back
@dataclass
class Request:
id: int
name: str
results: List[str] = field(default_factory=list)
# --- Core Components ---
class CircuitBreaker:
"""
Manages the state of connection to a remote service to prevent cascading failures.
"""
def __init__(self, failure_threshold=3, recovery_timeout=5.0):
self.failure_count = 0
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.state = CircuitState.CLOSED
self.last_failure_time = 0
async def call(self, service, request):
if self.state == CircuitState.OPEN:
# Check if we should try to recover
if time.time() - self.last_failure_time > self.recovery_timeout:
self.state = CircuitState.HALF_OPEN
print(f"[CircuitBreaker] Entering HALF-OPEN for {service.name}")
else:
raise Exception(f"Circuit OPEN for {service.name} (Failing Fast)")
try:
response = await service.handle_request(request)
self.on_success()
return response
except Exception as e:
self.on_failure()
raise e
def on_success(self):
if self.state == CircuitState.HALF_OPEN:
print(f"[CircuitBreaker] Recovery successful. Closing Circuit.")
self.state = CircuitState.CLOSED
self.failure_count = 0
def on_failure(self):
self.failure_count += 1
self.last_failure_time = time.time()
if self.failure_count >= self.failure_threshold or self.state == CircuitState.HALF_OPEN:
if self.state != CircuitState.OPEN:
print(f"[CircuitBreaker] Threshold reached. Opening Circuit!")
self.state = CircuitState.OPEN
class Microservice:
def __init__(self, name: str, dependencies: List[str] = None):
self.name = name
self.status = ServiceStatus.HEALTHY
self.dependencies = dependencies or []
self.clients: Dict[str, 'Microservice'] = {} # Filled by Orchestrator
self.circuit_breakers: Dict[str, CircuitBreaker] = {}
async def handle_request(self, request: Request):
"""
Simulate processing logic.
"""
if self.status == ServiceStatus.DOWN:
raise Exception(f"Service {self.name} is DOWN (Connection Refused)")
# Simulate Latency
latency = 0.05
if self.status == ServiceStatus.STRUGGLING:
latency = random.uniform(0.5, 2.0)
await asyncio.sleep(latency)
# Logic: Call dependencies
for dep_name in self.dependencies:
if dep_name not in self.circuit_breakers:
self.circuit_breakers[dep_name] = CircuitBreaker()
cb = self.circuit_breakers[dep_name]
dep_service = self.clients[dep_name]
try:
await cb.call(dep_service, request)
except Exception as e:
# In a real app, we might handle this differently (fallback)
# Here we let it bubble up to show failure propagation
raise Exception(f"Failed calling {dep_name}: {str(e)}")
request.results.append(f"Processed by {self.name}")
return request
def __repr__(self):
return f"[{self.name} | {self.status.name}]"
# --- The Simulation Environment ---
class ArchitectureSimulator:
def __init__(self):
self.services: Dict[str, Microservice] = {}
self.request_counter = 0
self.setup_architecture()
def setup_architecture(self):
"""
Defines the topology:
Gateway -> OrderService -> InventoryService
-> PaymentService
"""
# 1. Create Services
inventory = Microservice("Inventory-Service")
payment = Microservice("Payment-Service")
order = Microservice("Order-Service", dependencies=["Inventory-Service", "Payment-Service"])
gateway = Microservice("API-Gateway", dependencies=["Order-Service"])
# 2. Register them
for svc in [gateway, order, inventory, payment]:
self.services[svc.name] = svc
# 3. Wire them up (Dependency Injection)
# In a real scenario, this is a service registry/discovery
order.clients = {"Inventory-Service": inventory, "Payment-Service": payment}
gateway.clients = {"Order-Service": order}
self.gateway = gateway
async def run_traffic_generator(self):
"""Simulates users hitting the system."""
while True:
self.request_counter += 1
req = Request(id=self.request_counter, name=f"UserOrder_{self.request_counter}")
# Fire and forget (don't await) to simulate concurrent users
asyncio.create_task(self.process_user_request(req))
await asyncio.sleep(REQUEST_INTERVAL)
async def process_user_request(self, request: Request):
try:
await self.gateway.handle_request(request)
print(f"✅ SUCCESS: Request {request.id} completed. Path: {' -> '.join(request.results)}")
except Exception as e:
print(f"❌ FAILED: Request {request.id} failed. Reason: {e}")
async def run_chaos_monkey(self):
"""Randomly kills or slows down services."""
while True:
await asyncio.sleep(CHAOS_INTERVAL)
target_name = random.choice(list(self.services.keys()))
target = self.services[target_name]
# Skip the Gateway for chaos to ensure traffic always enters the system
if target_name == "API-Gateway": continue
action = random.choice(["KILL", "STRESS", "HEAL"])
if action == "KILL":
print(f"\n🔥 CHAOS: Killing {target_name}!")
target.status = ServiceStatus.DOWN
elif action == "STRESS":
print(f"\n⚠️ CHAOS: Overloading {target_name} (High Latency)!")
target.status = ServiceStatus.STRUGGLING
elif action == "HEAL":
if target.status != ServiceStatus.HEALTHY:
print(f"\n🔧 CHAOS: Fixing {target_name}!")
target.status = ServiceStatus.HEALTHY
async def monitor(self):
"""Simple dashboard printout."""
while True:
await asyncio.sleep(5.0)
print("\n--- System Status ---")
for name, svc in self.services.items():
cbs = []
for dep, cb in svc.circuit_breakers.items():
if cb.state != CircuitState.CLOSED:
cbs.append(f"{dep}({cb.state.name})")
cb_str = f" | Circuits: {', '.join(cbs)}" if cbs else ""
print(f"{name}: {svc.status.name}{cb_str}")
print("---------------------\n")
async def start(self):
print("Starting Microservice Simulator...")
print("Architecture: Gateway -> Order -> (Inventory, Payment)")
print("Close with Ctrl+C\n")
await asyncio.gather(
self.run_traffic_generator(),
self.run_chaos_monkey(),
self.monitor()
)
# --- Entry Point ---
if __name__ == "__main__":
sim = ArchitectureSimulator()
try:
asyncio.run(sim.start())
except KeyboardInterrupt:
print("\nSimulation stopped.")
What you will see
When you run the script, you will see a live log of requests.
- Happy Path:
Requests flow from
Gateway -> Order -> Inventory/Payment. You see ✅ SUCCESS.
- Chaos Engineering:
Every few seconds, the Chaos Monkey acts.
- Example:
🔥 CHAOS: Killing Inventory-Service!
- Failure Propagation:
Immediately after a kill, you will see
❌ FAILED for requests trying to access inventory.
- Circuit Breaking:
If you look closely at the logs (or the periodic Status Board), you will see
CircuitBreaker messages.
- The
Order service detects Inventory is down.
- It opens the circuit.
- Subsequent requests fail instantly (Failing Fast) without waiting for a network timeout. This saves system resources.
- Recovery:
Eventually, the Chaos Monkey will
HEAL the service. The Circuit Breaker enters HALF-OPEN, tries a request, succeeds, and closes the circuit. Traffic resumes.