Concept: Model microservice dependencies as a directed graph. Two recurring architect questions: “if service X goes down, what else breaks?” (blast radius via BFS on the dependents graph) and “do we have a circular dependency?” (cycle detection via DFS with three-coloring).
Python Implementation
from collections import defaultdict, deque
class ServiceGraph:
def __init__(self):
self.dependencies = defaultdict(set) # service -> services it depends on
self.dependents = defaultdict(set) # service -> services that depend on it
def add_dependency(self, service: str, depends_on: str) -> None:
self.dependencies[service].add(depends_on)
self.dependents[depends_on].add(service)
def blast_radius(self, failed_service: str) -> set[str]:
"""BFS over the reverse graph: everything that transitively depends on the failed service."""
affected = set()
queue = deque([failed_service])
while queue:
service = queue.popleft()
for dependent in self.dependents.get(service, []):
if dependent not in affected:
affected.add(dependent)
queue.append(dependent)
return affected
def has_circular_dependency(self) -> bool:
"""DFS with WHITE/GRAY/BLACK coloring; a back-edge (GRAY->GRAY) means a cycle."""
WHITE, GRAY, BLACK = 0, 1, 2
color = defaultdict(int)
def dfs(node):
color[node] = GRAY
for dep in self.dependencies.get(node, []):
if color[dep] == GRAY:
return True
if color[dep] == WHITE and dfs(dep):
return True
color[node] = BLACK
return False
all_services = set(self.dependencies) | set(self.dependents)
return any(dfs(s) for s in all_services if color[s] == WHITE)
def topological_order(self) -> list[str]:
"""Kahn's algorithm — returns a valid deploy order, raises if a cycle exists."""
in_degree = defaultdict(int)
all_services = set(self.dependencies) | set(self.dependents)
for s in all_services:
in_degree[s] # ensure entry exists
for s, deps in self.dependencies.items():
for d in deps:
in_degree[s] += 0 # placeholder, edge direction handled below
# Edge convention: service -> depends_on means depends_on must be deployed first.
in_deg = {s: 0 for s in all_services}
for s, deps in self.dependencies.items():
in_deg[s] += len(deps)
queue = deque([s for s in all_services if in_deg[s] == 0])
order = []
while queue:
node = queue.popleft()
order.append(node)
for dependent in self.dependents.get(node, []):
in_deg[dependent] -= 1
if in_deg[dependent] == 0:
queue.append(dependent)
if len(order) != len(all_services):
raise ValueError("Cycle detected — no valid topological order")
return order
# --- Usage ---
g = ServiceGraph()
g.add_dependency("OrderService", "PaymentDB")
g.add_dependency("CartService", "OrderService")
g.add_dependency("WebApp", "CartService")
g.add_dependency("WebApp", "AuthService")
print(g.blast_radius("PaymentDB")) # {'OrderService', 'CartService', 'WebApp'}
print(g.has_circular_dependency()) # False
C# Implementation
using System;
using System.Collections.Generic;
using System.Linq;
public class ServiceGraph
{
private readonly Dictionary<string, HashSet<string>> _dependencies = new();
private readonly Dictionary<string, HashSet<string>> _dependents = new();
public void AddDependency(string service, string dependsOn)
{
if (!_dependencies.TryGetValue(service, out var deps))
{
deps = new HashSet<string>();
_dependencies[service] = deps;
}
deps.Add(dependsOn);
if (!_dependents.TryGetValue(dependsOn, out var dependents))
{
dependents = new HashSet<string>();
_dependents[dependsOn] = dependents;
}
dependents.Add(service);
}
public HashSet<string> BlastRadius(string failedService)
{
var affected = new HashSet<string>();
var queue = new Queue<string>();
queue.Enqueue(failedService);
while (queue.Count > 0)
{
var service = queue.Dequeue();
if (!_dependents.TryGetValue(service, out var dependents)) continue;
foreach (var dependent in dependents)
{
if (affected.Add(dependent))
queue.Enqueue(dependent);
}
}
return affected;
}
public bool HasCircularDependency()
{
var color = new Dictionary<string, int>(); // 0=white,1=gray,2=black
var allServices = _dependencies.Keys.Union(_dependents.Keys).ToList();
bool Dfs(string node)
{
color[node] = 1;
if (_dependencies.TryGetValue(node, out var deps))
{
foreach (var dep in deps)
{
if (color.GetValueOrDefault(dep) == 1) return true;
if (!color.ContainsKey(dep) && Dfs(dep)) return true;
}
}
color[node] = 2;
return false;
}
return allServices.Any(s => !color.ContainsKey(s) && Dfs(s));
}
public List<string> TopologicalOrder()
{
var allServices = _dependencies.Keys.Union(_dependents.Keys).ToHashSet();
var inDegree = allServices.ToDictionary(s => s, s => 0);
foreach (var (service, deps) in _dependencies)
inDegree[service] += deps.Count;
var queue = new Queue<string>(allServices.Where(s => inDegree[s] == 0));
var order = new List<string>();
while (queue.Count > 0)
{
var node = queue.Dequeue();
order.Add(node);
if (!_dependents.TryGetValue(node, out var dependents)) continue;
foreach (var dependent in dependents)
{
if (--inDegree[dependent] == 0)
queue.Enqueue(dependent);
}
}
if (order.Count != allServices.Count)
throw new InvalidOperationException("Cycle detected — no valid topological order");
return order;
}
}
Complexity & Real-World Application
| Operation | Time | Space |
|---|---|---|
| Blast radius (BFS) | O(V+E) | O(V) |
| Cycle detection (DFS) | O(V+E) | O(V) |
| Topological sort (Kahn’s) | O(V+E) | O(V) |
This exact pattern is what underlies real observability tooling: PagerDuty/Datadog “service dependency maps” use blast-radius BFS to auto-suggest who to page during an incident, and CI/CD deploy-order tooling (Helm chart dependency resolution, Terraform’s DAG) uses topological sort to determine safe deployment sequencing.