Composite intent (part-whole trees with a uniform interface), leaf vs composite, a permission-group or rule tree in C#, .NET examples (CompositeFileProvider, CompositeChangeToken, expression trees), recursion depth and StackOverflowException, cycle detection, and storing hierarchies (recursive CTE, hierarchyid).
Composite models part-whole trees so clients treat a single item and a group the same way. Both implement one interface, and a composite holds children of that interface and aggregates their results.
Typical uses are permission groups that contain permissions and other groups, rule trees (All/Any of child rules), menus and org charts. .NET uses it in CompositeFileProvider, CompositeChangeToken, and expression and syntax trees.
The danger is recursion. A cycle (group A contains B contains A) or a very deep tree overflows the stack, and StackOverflowException can't be caught: it kills the process. Guard with a visited set, a depth limit or an iterative traversal, and reject cycles when data is saved.
"Composite is for trees where a group should behave like a single item. You define one interface, say
IPermissionNodewithGrants(string permission). A leaf, a single permission, answers directly. A composite, a group, holds a list ofIPermissionNodechildren and answers by asking them. The client never checks whether it has a leaf or a group; it just callsGrants. Rules engines use the same shape: anAllOfrule is true when every child is true, anAnyOfwhen at least one is, and leaves are simple checks like 'order total over $500' or 'customer in NSW'. You can build arbitrarily complex rules from small pieces.In .NET,
CompositeFileProvidermakes severalIFileProviders look like one, which is how ASP.NET Core serves static files from yourwwwrootand from Razor class libraries together.CompositeChangeTokenfires when any child token fires. Expression trees and Roslyn syntax trees are composites too: aBinaryExpressioncontains two child expressions.The mistake I see is trusting the data to be a tree. Permission groups are usually editable by admins, and sooner or later someone puts group A inside group B and B inside A. The recursive check never ends, and
StackOverflowExceptioncan't be caught, so the whole process dies and every request on that instance fails. I guard it in two places. When saving, I reject a change that would create a cycle. When evaluating, I keep a visited set or switch to an iterative traversal with an explicitStack<T>, plus a maximum depth. A composite is only safe if you enforce that it really is a tree."
| Role | Permission example | Rules example |
|---|---|---|
| Component | IPermissionNode |
IRule |
| Leaf | Permission("orders.refund") |
MinTotal(500), InState("NSW") |
| Composite | PermissionGroup(children) |
AllOf(rules), AnyOf(rules), Not(rule) |
| Approach | Depth limit | Cycle safe | Notes |
|---|---|---|---|
| Naive recursion | Stack size (~1 MB main thread) | No | Simple; crashes the process on cycles |
| Recursion + visited set | Stack size | Yes | Easy fix for cycles |
| Recursion + max depth | Configured | Yes (stops) | Fails a request instead of the process |
Iterative with Stack<T>/Queue<T> |
Heap | With visited set | Best for user-editable data |
A SaaS admin portal let customers nest role groups. One customer created a cycle while reorganising, and the permission check recursed until StackOverflowException killed each instance as it handled that customer's requests. App Service restarted instances in a loop for 25 minutes. The fix added cycle validation on save and an iterative, visited-set evaluation; the next attempted cycle returned a 400 instead of an outage.
Checks understanding of uniform treatment of part-whole hierarchies, and the reliability risks of recursive structures.
Green flags
CompositeFileProvider).StackOverflowException unprompted.Red flags
StackOverflowException can be caught.Client βββΆ Β«interfaceΒ» Component
+ Operation()
β² β²
Leaf Composite ββ children: List<Component>
Operation() => aggregate(children.Select(c => c.Operation()))
GoF discusses where to put child management (Add, Remove). Putting it on the component interface gives transparency (clients treat everything the same) but leaves must throw on Add. Putting it only on the composite gives safety but clients must know the type to add children. In C# I keep the shared interface to the operations (Grants, IsSatisfiedBy) and construct trees with composite-specific constructors or builders.
Each recursive call uses a stack frame. The default stack is about 1 MB for the main thread and for thread-pool threads on Windows (8 MB by default on Linux, depending on ulimit). Since .NET 2.0, StackOverflowException can't be caught and the runtime terminates the process. A cycle makes recursion infinite; a legitimately deep tree (thousands of levels) can also overflow. An explicit Stack<T> lives on the heap, so depth is bounded by memory, not the thread stack.
CompositeFileProvider(params IFileProvider[]): GetFileInfo returns the first provider's existing file; GetDirectoryContents merges.CompositeChangeToken(IReadOnlyList<IChangeToken>): HasChanged if any child has changed; used by configuration and file watching.System.Linq.Expressions.Expression: binary, unary, method-call nodes containing child expressions; ExpressionVisitor walks them (the Visitor pattern over a Composite).| Model | Query subtree | Move subtree | Notes |
|---|---|---|---|
Adjacency list (ParentId) |
Recursive CTE | Update one row | Simple; CTE MAXRECURSION default 100 protects from cycles but errors |
hierarchyid (SQL Server; EF Core 8+) |
IsDescendantOf index seek |
Rewrite descendants | Fast subtree queries; trees only |
| Closure table | Join | Many row changes | Supports DAGs (a group in several parents) |
Permission groups that can belong to several parents are a DAG, not a tree: a node can be reached twice without a cycle, so the visited set also avoids evaluating it twice.
Stack<T> and a HashSet<Guid> of visited groups.MAXRECURSION).IFileProviders with CompositeFileProvider and list the merged directory contents.A rules composite and a cycle-safe permission evaluation:
namespace Rules;
public sealed record OrderContext(decimal Total, string State, bool IsNewCustomer);
public interface IRule
{
bool IsSatisfiedBy(OrderContext order);
}
// Leaves
public sealed record MinTotal(decimal Amount) : IRule
{
public bool IsSatisfiedBy(OrderContext o) => o.Total >= Amount;
}
public sealed record InState(string State) : IRule
{
public bool IsSatisfiedBy(OrderContext o) => string.Equals(o.State, State, StringComparison.OrdinalIgnoreCase);
}
// Composites
public sealed record AllOf(params IRule[] Rules) : IRule
{
public bool IsSatisfiedBy(OrderContext o) => Rules.All(r => r.IsSatisfiedBy(o));
}
public sealed record AnyOf(params IRule[] Rules) : IRule
{
public bool IsSatisfiedBy(OrderContext o) => Rules.Any(r => r.IsSatisfiedBy(o));
}
// Free shipping: total >= $100 AND (NSW OR VIC)
// IRule freeShipping = new AllOf(new MinTotal(100m), new AnyOf(new InState("NSW"), new InState("VIC")));
namespace Security;
public abstract record PermissionNode(Guid Id);
public sealed record Permission(Guid Id, string Name) : PermissionNode(Id);
public sealed record PermissionGroup(Guid Id, string Name, IReadOnlyList<PermissionNode> Children) : PermissionNode(Id);
public static class PermissionEvaluator
{
private const int MaxNodes = 10_000;
// Iterative: no recursion, so no stack overflow; visited set handles cycles and shared subgroups
public static bool Grants(PermissionNode root, string permission)
{
var pending = new Stack<PermissionNode>();
var visited = new HashSet<Guid>();
pending.Push(root);
while (pending.TryPop(out PermissionNode? node))
{
if (!visited.Add(node.Id)) continue; // already seen: cycle or shared group
if (visited.Count > MaxNodes) throw new InvalidOperationException("Permission tree too large.");
switch (node)
{
case Permission p when p.Name == permission:
return true;
case PermissionGroup g:
foreach (PermissionNode child in g.Children) pending.Push(child);
break;
}
}
return false;
}
// Validate on save: would adding 'child' under 'parent' create a cycle?
public static bool WouldCreateCycle(PermissionGroup parent, PermissionGroup child) =>
child.Id == parent.Id || Contains(child, parent.Id);
private static bool Contains(PermissionNode root, Guid targetId)
{
var pending = new Stack<PermissionNode>([root]);
var visited = new HashSet<Guid>();
while (pending.TryPop(out PermissionNode? n))
{
if (n.Id == targetId) return true;
if (visited.Add(n.Id) && n is PermissionGroup g)
foreach (PermissionNode c in g.Children) pending.Push(c);
}
return false;
}
}
-- All permissions for a role, following nested groups (adjacency list)
WITH Tree AS (
SELECT ChildId, 1 AS Depth FROM GroupMembers WHERE GroupId = @RoleId
UNION ALL
SELECT gm.ChildId, t.Depth + 1
FROM GroupMembers gm JOIN Tree t ON gm.GroupId = t.ChildId
WHERE t.Depth < 20 -- explicit depth guard
)
SELECT DISTINCT p.Name
FROM Tree t JOIN Permissions p ON p.Id = t.ChildId;
StackOverflowException kills the process. Instead: Validate on save and use visited sets or iterative traversal on read.Add/Remove on the shared interface and throwing in leaves. Why it is wrong: Callers get run-time errors for operations the type system allowed. Instead: Keep the shared interface to the operations; build trees through composite constructors.hierarchyid or a closure table, then build the tree in memory.Any stops early). Why it is wrong: Children with logging or I/O behave differently depending on order. Instead: Keep leaf evaluation pure, or make short-circuiting explicit.Composite is a natural fit for rules and permissions, and it's elegant until the data comes from users. Then it becomes a reliability problem: one bad edit can crash every instance that evaluates it. I treat the tree invariant as something the system enforces, not something it hopes for.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| In-memory composite (code-defined rules) | Rules known at compile time | None | Business users edit rules |
| Composite built from DB data | Admin-editable groups and rules | Validation, caching | Very large or very dynamic graphs |
| Flattened permissions (precomputed) | Read-heavy authorisation checks | Recompute on change | Frequent structural edits |
| Policy engine (e.g. ASP.NET Core authorisation policies) | Authorisation with requirements and handlers | Framework concepts | Complex arbitrary nesting |
For hot authorisation paths I often flatten the composite on write (a user's effective permission set, cached) so reads are a set lookup, and keep the composite only for editing.
A tree is a hierarchy of nodes with one root, where each node has children and no cycles. A binary tree limits each node to two children (left, right). A binary search tree (BST) adds an ordering rule: left subtree < node < right subtree, so search, insert and delete take O(height).
If the tree is balanced, height is O(log n); if you insert sorted data into a plain BST it degenerates into a linked list with O(n) height. Self-balancing trees (red-black, AVL) keep O(log n); .NET's SortedSet and SortedDictionary are red-black trees.
Traversals: in-order (sorted output for a BST), pre-order (copy/serialise), post-order (delete/evaluate), level-order (BFS).
Trees are everywhere: database B+ tree indexes, file systems, JSON/XML/DOM, Roslyn syntax trees, expression trees, org charts.
Each thread has a fixed-size stack (about 1 MB on Windows), and every method call pushes a frame. Unbounded or very deep recursion exhausts it. Since .NET 2.0 the runtime terminates the process on a stack overflow instead of throwing a catchable exception, because with no stack left it can't safely run handlers or finally blocks. To diagnose it, I read the crash output (recent .NET versions print the repeating frames to standard error), check container logs or the Windows Event Log, and capture a crash dump with DOTNET_DbgEnableMiniDump=1 to inspect the stack. Typical causes are a missing base case, a property or ToString that calls itself, cycles in object graphs (serialisation, Equals), and deeply nested input. Fixes: correct the recursion, switch to iteration with an explicit stack, and add depth limits and tests.
How to tell it (STAR)
**S:** At [company] all [four] instances of our admin portal started restarting in a loop, with no exceptions in our telemetry. **T:** I needed to stop the outage and find a cause that left no logs. **A:** The event log showed a `StackOverflowException`, which can't be caught, so I took a crash dump: thousands of frames in our recursive permission check. A tenant had just made two role groups contain each other. I deleted the bad row to restore service within [25 minutes], then added cycle validation on save and rewrote the evaluator iteratively with a visited set. **R:** The next attempted cycle got a [400] instead of an outage, and permission checks got [~30%] faster because shared groups were no longer evaluated twice.
Last updated 18 Nov 2026.