Scrivio Interview library
LeadershipPrincipal7 min read · updated 12 November 2026

Recursive designs keep appearing in your products: recursive JSON parsers, recursive SQL for org charts, recursive permission resolution across group hierarchies. Several outages came from unbounded depth or cycles. What engineering standards would you set across the company?

The standard I would set is that every recursive structure fed by external or user-controlled data has explicit, configurable limits on depth and size, every graph-like traversal has cycle detection, and every recursive SQL query has a depth guard, a cycle check and a statement timeout. Deeply nested payloads are treated as a denial-of-service risk, so they appear in threat models and fuzz tests, and every limit is observable, so support sees a named limit being hit instead of a StackOverflowError or a timeout.

Background to this question

Recursion is not the problem in these outages; unbounded input is. A JSON document nested 100,000 levels deep, an org chart where someone reports to their own report, a group that contains itself: each turns a correct recursive algorithm into a crash or a hang. A senior leader is expected to see that these separate incidents share one cause and to set a small number of standards that make the safe path the default. In this answer, we will look at why these outages keep happening, then go through limits on parsers and payloads, cycle detection for graph data, guards for recursive SQL, treating nesting as a security concern, making limits visible, and how to roll the standards out.

1Why Recursive Designs Keep Failing the Same Way

A recursive algorithm has an implicit assumption: the input has finite, modest depth and no cycles. Tests use friendly data, so the assumption holds in development. In production, input comes from customers, imports, integrations and attackers, and some of it breaks the assumption. When depth is unbounded, the JVM runs out of stack and throws StackOverflowError, or a database query recurses until it uses all its memory. When there is a cycle, the walk never ends.

So the useful standard is not "avoid recursion", which would ban perfectly good code, but "never trust the shape of external data". Every place where data with a recursive shape enters the company needs a stated limit, and every traversal of data that can contain cycles needs a way to notice them.

2Standard 1: Explicit Depth and Size Limits on Parsers and Payloads

Parsers are the first line. Jackson, the JSON library behind Spring Boot, has StreamReadConstraints since version 2.15, with limits on nesting depth (the default maximum is 1000 in recent versions), number length and string length; check your version for the exact defaults. We require every service to keep these limits on, and to set them deliberately rather than raise them to make an error go away. The same applies to XML parsers (entity expansion and depth), YAML, and GraphQL, where graphql-java offers instrumentation to cap query depth and complexity.

Java
@Bean
Jackson2ObjectMapperBuilderCustomizer jsonLimits() {
return builder -> builder.postConfigurer(mapper ->
mapper.getFactory().setStreamReadConstraints(
StreamReadConstraints.builder()
.maxNestingDepth(64) // our payloads never nest deeper than about 10
.maxStringLength(1_000_000)
.build()));
}
// A request nested 65 levels deep -> StreamConstraintsException -> 400 Bad Request

Notice that the limit is set from what our real payloads need, with headroom, not from what the library allows. A limit of 64 when real data nests 10 deep stops abuse long before it can stress the stack. Request body size limits at the gateway complete the picture. In Jackson 3, used by Spring Boot 4, the builder API differs, so the platform team should ship this as a shared configuration rather than each team writing it.

3Standard 2: Cycle Detection and Iterative Traversal for Graph Data

Groups that contain groups, categories, folders, org charts and bills of materials are graphs, even when we think of them as trees, because any data entry or import mistake can create a cycle. The standard is that service code traversing such data does so iteratively, with an explicit ArrayDeque and a visited set, and with a depth limit that matches the business. Group nesting deeper than 10 is a data problem to report, not something to traverse. We also prevent cycles at write time: before adding "group A contains group B", the service checks that A is not reachable from B.

A shared library function such as Graphs.walk(start, children, maxDepth) that does all of this correctly is worth more than a guideline, because teams will use the function that already exists.

4Standard 3: Guards on Recursive SQL

Recursive SQL with WITH RECURSIVE is powerful for org charts and hierarchies, and it fails the same way: a cycle makes the recursive part produce rows forever. Every recursive query must carry a depth column with a maximum, a cycle check, and run under a statement timeout.

SQL
SET statement_timeout = '2s';
WITH RECURSIVE chain AS (
SELECT id, manager_id, 1 AS depth
FROM employee WHERE id = 42
UNION ALL
SELECT e.id, e.manager_id, c.depth + 1
FROM employee e JOIN chain c ON e.id = c.manager_id
WHERE c.depth < 20 -- depth guard
) CYCLE id SET is_cycle USING path -- PostgreSQL 14 and later
SELECT * FROM chain WHERE NOT is_cycle;

The CYCLE clause marks a row whose id already appeared on its path and stops recursing from it. On databases or versions without it, we carry an array of visited ids and test membership. The depth guard alone also stops a cycle, but only after 20 rounds, and the timeout is the last line of defence when both are wrong.

5Standard 4: Treat Deep Nesting as a Security Concern

A payload nested 50,000 levels deep is a cheap denial-of-service attack: one small request can crash a worker thread or occupy a CPU. So nesting depth belongs in the threat model of every endpoint that accepts structured input, next to body size and rate limits. We add deep-nesting and cyclic inputs to fuzz tests, for example with Jazzer for Java code, and to the shared test fixtures, so a new parser or endpoint is tested against them by default.

6Standard 5: Make Every Limit Configurable and Observable

A limit that fails silently, or fails as a StackOverflowError deep in a stack trace, leads to the same long incident as no limit. Each limit has a name, a configured value, a clear error (400 Bad Request with "nesting depth exceeds 64" for an API, a rejected import with the offending ids for a batch job), a log line and a metric counter. Support can then see in a dashboard that the group depth limit was hit 30 times today for one tenant, and the conversation becomes about that tenant's data instead of a mystery crash.

Step throughWhat happens when a recursive limit is hit
  1. Input arrivesAPI body, import file, membership change
  2. Within depth, size and cycle limits?
    YesProcess normallyNoReject with a named limit
  3. Return a clear error400 or rejected import, with the limit's name
  4. Count and log itmetric per limit, tenant and endpoint
  5. Alert when the rate is unusualsupport sees the cause, not a crash

5 steps in order. Play them, or step through them one at a time.

7Rolling the Standards Out

Standards spread when they come with tools and evidence. We publish them as a short document that cites the actual outages, ship the shared Jackson configuration, the graph walk helper and a recursive SQL template, add a lint rule or architecture test that flags recursive methods over externally supplied structures for review, and add the checks to the design review template. We start with the services that had outages, then apply the standards to new work, and review the metric dashboards after a quarter to see which limits are hit and whether any need tuning.

8Follow-up questions

Would you ban recursion in service code?

No. Recursion over data we control, such as a fixed configuration tree or a small parsed expression, is clear and safe. The standard targets recursive processing of data whose shape comes from outside, where depth and cycles are not under our control. For that data we prefer iterative traversal with explicit limits.

How do you choose the limit values?

From the data. We measure the real distribution, for example the deepest group nesting in production is 7, and set the limit with generous headroom, say 20. A limit far above any real value still stops pathological input, and the metrics tell us if legitimate data ever approaches it.

What about recursion in third-party libraries?

We cannot rewrite them, so we bound their input: parser constraints, payload size limits and depth checks before the data reaches the library. We also include library-processed inputs in fuzz testing, since many past parser vulnerabilities were exactly deep-nesting crashes.

9Conclusion

In this answer, we saw that the outages come from trusting the shape of external data, not from recursion itself. The standards are explicit depth and size limits on every parser and payload, with Jackson's StreamReadConstraints as an example; iterative traversal with visited sets and write-time cycle checks for graph data; depth columns, cycle clauses and statement timeouts on recursive SQL; deep nesting treated as a denial-of-service concern in threat models and fuzz tests; and named, configurable, observable limits. Shared tools and outage evidence make teams adopt them.

What to say in the interviewAbout 80 seconds aloud

Open with

I would frame the standard as: never trust the shape of external data, rather than never use recursion. Concretely, first, every parser and endpoint that accepts nested data has explicit depth and size limits, for example Jackson's StreamReadConstraints with a nesting depth set from what our real payloads need, plus body size limits and GraphQL query depth limits.

Then, if they want more

Second, any graph-like data, groups in groups, categories, org charts, gets cycle detection: service code traverses it iteratively with a deque and a visited set and a business depth limit, and we prevent cycles at write time by checking reachability before adding an edge.

Third, every WITH RECURSIVE query has a depth column with a maximum, a cycle guard such as PostgreSQL's CYCLE clause, and a statement timeout. Fourth, deep nesting is a denial-of-service risk, so it goes into threat models and fuzz tests.

Fifth, every limit is configurable and observable: a named error, a log line and a metric, so support sees the group depth limit was hit instead of a StackOverflowError. I would roll it out with shared configuration and helpers, starting with the services that had outages, and review the limit metrics after a quarter.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 14, Spring Boot 4
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 "Recursive designs keep appearing in your products: recursive JSON parsers, recursive SQL...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/93f0bda6e2/