Quick revision
The short answer
A valid startup order is a topological sort of the dependency graph: every service appears after all the services it depends on. Kahn's algorithm computes each service's in-degree (how many dependencies it still waits for), starts from the services with none, and each time it starts one, decrements the count of the services that depend on it. If the result has fewer services than the graph, the rest are stuck behind a cycle, which we report; a DFS with three colours finds the exact cycle path. Both run in O(V + E) time and space, and Spring detects circular bean references at startup in a similar way.
What to remember
In this answer, we modelled service dependencies as a directed graph with edges from each dependency to the service that needs it, so a valid startup order is a topological sort. Kahn's algorithm counts in-degrees, starts with services that depend on nothing, and decrements dependents as each one starts; if the order is shorter than the graph, the remaining services are blocked by a cycle. A three-colour DFS finds the exact cycle path through back edges. Both run in O(V + E), and Spring detects circular bean references at startup with the same idea of tracking beans in creation.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
A valid startup order is a topological sort of the dependency graph: every service appears after all the services it depends on. Kahn's algorithm computes each service's in-degree (how many dependencies it still waits for), starts from the services with none, and each time it starts one, decrements the count of the services that depend on it. If the result has fewer services than the graph, the rest are stuck behind a cycle, which we report; a DFS with three colours finds the exact cycle path. Both run in O(V + E) time and space, and Spring detects circular bean references at startup in a similar way.
Why this question is asked
Ordering things by their dependencies is one of the most practical graph algorithms: build systems order modules, package managers order installs, schedulers order jobs, and Spring orders bean creation. Interviewers ask for it because it combines graph modelling, a clean algorithm and careful edge cases, and because cycle reporting is what makes it useful in real systems. In this answer, we will model the problem as a graph, walk through Kahn's algorithm, write it in Java, see how it reports cycles, look at the DFS alternative that finds the cycle path, and connect it to how Spring starts beans.
1Modelling Dependencies as a Graph
The input Map<String, List<String>> says, for each service, which services it depends on: web depends on auth and catalog, so auth and catalog must start before web. We turn this into a directed graph where an edge goes from a dependency to the service that needs it, auth -> web. A startup order is then an ordering of the nodes where every edge points forwards, which is exactly a topological order.
Two details matter. Services that appear only as dependencies, such as db, which no one lists as a key, are still nodes. And a topological order exists only if the graph has no directed cycle: if auth needs db and db needs auth, neither can start first.
| Service | Depends on | In-degree |
|---|---|---|
| web | auth, catalog | 2 |
| auth | db | 1 |
| catalog | db, cache | 2 |
| db | nothing | 0 |
| cache | nothing | 0 |
2How Kahn's Algorithm Works
Kahn's algorithm is the natural way to think about startup. First, count each service's in-degree. Every service with in-degree 0 can start now, so it goes into a queue. Then we repeatedly take a service from the queue, append it to the order, and for each service that depends on it, decrement that service's in-degree, because one of its dependencies is now running. When a count reaches 0, that service is ready, so it joins the queue.
In the example, db and cache start first. Starting db reduces auth to 0 and catalog to 1; starting cache reduces catalog to 0; then auth and catalog start, which brings web to 0, and web starts last. The order is db, cache, auth, catalog, web. Services that are ready at the same time could start in parallel, which is a nice bonus: each round of the queue is a wave.
- Count in-degreesand record each service's dependents
- Queue every service with in-degree 0
- Queue empty?YesCheck the result sizeNoTake one, append to the order
- Decrement each dependentenqueue any that reach 0
- Back to the empty check
- Order has every service?YesReturn the orderNoReport a cycle among the rest
6 steps in order. Play them, or step through them one at a time.
3Writing It in Java
The code builds the dependents lists and in-degree counts, then runs the queue. LinkedHashMap keeps the output deterministic, which makes it easier to test and to read in logs.
Notice that a duplicate dependency in a list, such as auth listed twice for web, would count twice in the in-degree and also be decremented twice, so the algorithm stays correct; deduplicating the lists first is still cleaner.
4Detecting and Reporting Cycles
If there is a cycle, the services in it never reach in-degree 0, because each waits for another one in the cycle. The queue empties early and the order is shorter than the number of services. Everything left over is reported as blocked.
Notice that the blocked set contains more than the cycle itself: web and catalog are not in a cycle, they just depend on something that is. That is a correct report of what cannot start, but for fixing the configuration we want the cycle path, auth -> db -> auth, which DFS gives us.
5The DFS Alternative That Finds the Cycle Path
A depth-first search can also produce a topological order and, when it fails, the exact cycle. We give each node one of three colours: white for not visited, grey for in progress (on the current DFS path), and black for done. We visit a node's dependencies before finishing the node. If we ever reach a grey node, we have found a back edge, an edge back to a node on the current path, and the path from that grey node to here is a cycle. When a node turns black, we append it to the order, which places every service after its dependencies.
The arrow in this message points from a service to what it depends on. Recursion depth equals the longest dependency chain, which is fine for a few thousand services; for a huge generated graph, an iterative version with an explicit stack avoids stack overflow.
6Complexity and the Link to Spring
Both algorithms touch each service a constant number of times and each dependency edge once, so with V services and E dependency edges they run in O(V + E) time and use O(V + E) space for the adjacency lists and counts. For 2,000 services and 20,000 dependencies, that is microseconds.
Spring faces the same problem when it creates beans: a bean's constructor dependencies must be created first. As it creates beans, it tracks which ones are currently in creation, much like the grey colour. If it is asked for a bean that is still in creation, it has found a cycle and fails with BeanCurrentlyInCreationException, listing the beans involved. Since Spring Boot 2.6, circular references are prohibited by default (spring.main.allow-circular-references is false), so such a cycle stops the application at startup with a report of the cycle.
7Follow-up questions
How would you start independent services in parallel?
Process Kahn's queue in waves: take all services currently at in-degree 0 as one wave, start them in parallel, and when they are all healthy, decrement their dependents and form the next wave. In the example, wave 1 is db and cache, wave 2 is auth and catalog, and wave 3 is web.
Is the topological order unique?
Not in general. Whenever two services are ready at the same time, either can go first, so db, cache, auth, catalog, web and cache, db, catalog, auth, web are both valid. Using insertion-ordered maps, or sorting the ready queue, makes our output deterministic.
What if a dependency is optional?
Then it should not be a hard edge in the graph. We can model it as a soft edge that orders startup when both services exist but is dropped if it would create a cycle, or better, make the service tolerate the dependency being unavailable at startup and connect later.
8Conclusion
In this answer, we modelled service dependencies as a directed graph with edges from each dependency to the service that needs it, so a valid startup order is a topological sort. Kahn's algorithm counts in-degrees, starts with services that depend on nothing, and decrements dependents as each one starts; if the order is shorter than the graph, the remaining services are blocked by a cycle. A three-colour DFS finds the exact cycle path through back edges. Both run in O(V + E), and Spring detects circular bean references at startup with the same idea of tracking beans in creation.
Open with
I would treat it as a topological sort. Each service is a node and there is an edge from a dependency to the service that needs it, and I include services that only appear as dependencies.
Then, if they want more
With Kahn's algorithm I first compute each service's in-degree, the number of dependencies it waits for, and build a list of dependents for each service. All services with in-degree zero go into a queue.
Then I repeatedly take one, append it to the startup order, and decrement the in-degree of each of its dependents; any that reach zero join the queue. If at the end the order contains every service, that is a valid startup order.
If it is shorter, the leftovers never reached zero, which means they are on a cycle or depend on one, and I report them.
To give a precise error I would also run a DFS with three colours, white, grey for on the current path and black for done: reaching a grey node is a back edge, and the path from it gives the cycle, like auth to db to auth. Both are O(V plus E) in time and space.
A nice extension is processing the queue in waves to start independent services in parallel. Spring does essentially the same for beans: it tracks beans in creation and fails at startup with BeanCurrentlyInCreationException when it finds a cycle.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Boot 2.6
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Services declare dependencies on other services as a Map<String, List<String>>. Write an...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/94b21c5ee2/