📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

What is the Composite pattern? Show how you would model a tree of permissions, pricing rules or menu items so that clients treat single items and groups the same way, where .NET uses it, and how you guard against deep recursion and cycles.

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).

Mid-Level Theory Intermediate composite design-patterns permissions recursion rules-engine trees

🎯 Key points

  • Composite lets clients treat individual objects (leaves) and groups (composites) uniformly through one interface; composites hold children of that interface
  • Typical uses: permission groups containing permissions and other groups, pricing or eligibility rules combined with All/Any, menus, org charts, file systems; for a flat list a plain collection is simpler
  • .NET examples: CompositeFileProvider (several IFileProviders as one), CompositeChangeToken, expression trees and Roslyn syntax trees
  • Operations recurse: a composite's result aggregates its children's results (All = every child true, Any = at least one)
  • Deep or cyclic trees can overflow the stack; a catch block for StackOverflowException never runs, because the runtime terminates the process
  • Guard with a visited set (cycle detection), a maximum depth, or an iterative traversal with Stack<T>/Queue<T>; validate on write, not just on read
  • Persist hierarchies with self-referencing tables and recursive CTEs (MAXRECURSION default 100), SQL Server's hierarchyid type (mapped natively by EF Core 8+) or closure tables
  • Trade-off: uniformity makes leaf-only or composite-only operations awkward (Add on a leaf), and shared subgroups in a DAG are re-evaluated unless memoised

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Composite is for trees where a group should behave like a single item. You define one interface, say IPermissionNode with Grants(string permission). A leaf, a single permission, answers directly. A composite, a group, holds a list of IPermissionNode children and answers by asking them. The client never checks whether it has a leaf or a group; it just calls Grants. Rules engines use the same shape: an AllOf rule is true when every child is true, an AnyOf when 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, CompositeFileProvider makes several IFileProviders look like one, which is how ASP.NET Core serves static files from your wwwroot and from Razor class libraries together. CompositeChangeToken fires when any child token fires. Expression trees and Roslyn syntax trees are composites too: a BinaryExpression contains 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 StackOverflowException can'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 explicit Stack<T>, plus a maximum depth. A composite is only safe if you enforce that it really is a tree."


Roles

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)

Traversal choices

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

Production example

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.

πŸ” What the interviewer is checking

Checks understanding of uniform treatment of part-whole hierarchies, and the reliability risks of recursive structures.

Green flags

  • Explains leaf and composite sharing one interface.
  • Gives a realistic example (permissions, rules) and a framework one (CompositeFileProvider).
  • Raises cycles, depth and the uncatchable StackOverflowException unprompted.
  • Knows how to persist and query hierarchies.

Red flags

  • Naive recursion over user-editable data.
  • Thinks StackOverflowException can be caught.
  • Uses Composite for flat collections.

πŸ“š Learn in depth

1. Structure

Client ──▢ Β«interfaceΒ» Component
               + Operation()
            β–²                 β–²
          Leaf            Composite ── children: List<Component>
                          Operation() => aggregate(children.Select(c => c.Operation()))

2. Transparency vs safety

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.

3. Why stack overflow is fatal in .NET

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.

4. Framework composites

  • 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).

5. Storing hierarchies

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.

Try it yourself

  1. Build a permission tree, add a cycle, and run a naive recursive check in a console app; observe the process crash.
  2. Rewrite it iteratively with Stack<T> and a HashSet<Guid> of visited groups.
  3. Write a recursive CTE that lists all permissions for a user and test it with a cycle (watch MAXRECURSION).
  4. Combine two IFileProviders with CompositeFileProvider and list the merged directory contents.

πŸ’» Code

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;

⚠ Common mistakes

  • Mistake: Assuming user-editable hierarchies are always trees. Why it is wrong: A cycle makes recursion infinite and StackOverflowException kills the process. Instead: Validate on save and use visited sets or iterative traversal on read.
  • Mistake: Evaluating shared subgroups repeatedly in a DAG. Why it is wrong: The same group reached through several parents is evaluated many times; cost can grow exponentially. Instead: Track visited nodes or memoise results.
  • Mistake: Putting 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.
  • Mistake: Loading a whole hierarchy with lazy loading, one level per query. Why it is wrong: A tree of depth d and width w issues many queries. Instead: Load with a recursive CTE, hierarchyid or a closure table, then build the tree in memory.
  • Mistake: Using Composite for a flat list. Why it is wrong: Extra types for no nesting. Instead: A collection and a loop.
  • Mistake: Composites with side effects that short-circuit unpredictably (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.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate talks about traversing the composite Why: Checks tree fundamentals and traversals
    How to answer

    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.

  2. When: Candidate mentions cycles causing a stack overflow Why: Checks diagnosing StackOverflowException crashes
    How to answer

    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.

πŸ›  Real-world problems: how you handle them

Cyclic permission group crashed every instance in a restart loop
Situation
A multi-tenant SaaS admin portal on .NET [10] in Azure App Service with [4] instances. Tenants could nest role groups; permission checks recursed through groups on every request.
Signals
App Service showed instances restarting every [1–2] minutes; Application Insights had no exception telemetry (the process died); the Windows event log on an instance showed 'Process terminated due to StackOverflowException'.
Investigation
Enabled crash dumps (`DOTNET_DbgEnableMiniDump`) and analysed one with `dotnet-dump analyze`: the stack was thousands of frames of `PermissionGroup.Grants`. Queried the group membership table and found a cycle created [minutes] earlier by one tenant reorganising roles.
Resolution
Immediate: removed the cyclic membership row in the database; instances stabilised. Real fix: cycle validation when adding a group to a group (400 with a clear message), and an iterative, visited-set evaluator with a node limit.
Prevention
Unit tests for cycles and shared subgroups; a database check job alerting on cycles; crash dumps enabled in production; precomputed effective permissions cached per user for the hot path.

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.

More in Structural Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me