Optimizing Tree Traversal with BFS
Learn how a level-by-level BFS eliminates the N+1 query problem by batching database queries, making hierarchical tree traversal faster and more scalable.
#From N+1 to O(Depth): Optimizing Cascading Soft Deletes with Level-by-Level BFS
In one of my recent projects, I had to implement a hierarchical artifact system. Since each artifact could have nested child artifacts, the data naturally formed a tree, making traversal and bulk operations an interesting challenge.
-
When a parent artifact is soft-deleted, every artifact beneath it in the hierarchy must be soft-deleted as well. Doing this efficiently is critical for database performance, especially as the platform scales.
-
In this article, I’ll walk through how I moved from a naive recursive approach to a highly optimized Level-by-Level Breadth-First Search (BFS), and share some under-the-hood raw BFS optimizations that separate tutorial code from production-ready systems.
#The Problem: The N+1 Query Trap
The most intuitive way to fetch all descendants of a node is recursively: fetch the children of the root, then for each child, fetch its children, and so on.
- While this works fine for small datasets, it leads to the infamous N+1 query problem. If an artifact tree has 100 nodes, you will execute 100 separate database queries. In a high-traffic application, this dramatically increases database round trips, connection pool exhaustion, and latency.
#The Solution: Level-by-Level BFS
Instead of querying the database for each node, we can query the database for each level.
-
By using a Breadth-First Search (BFS) approach, we can batch our database calls. For every level, we fetch the children of all parent nodes in a single query using a
WHERE parentArtifactId IN (...)clause. This batching strategy reduces the total number of queries to be proportional to the tree depth, not the total number of nodes. -
Since artifact trees are typically shallow, this approach is significantly more efficient while still guaranteeing we traverse every node.
Here is the implementation using Prisma and PostgreSQL:
async findDescendantIds(artifactId: string): Promise<string[]> {
// Collects every descendant discovered during the traversal. The root artifact itself is intentionally excluded.
const descendantIds: string[] = [];
// The set of nodes currently being explored. Initially this contains only the starting artifact, then it is replaced with the next level of children after each iteration.
let currentLevelIds = [artifactId];
// Continue traversing until there are no more levels remaining.
while (currentLevelIds.length > 0) {
/*
- Fetch every non-deleted artifact whose parent belongs to the current level.
- Example: currentLevelIds = ["B", "C"]
- Executes conceptually as: SELECT id FROM Artifact WHERE parentArtifactId IN ('B', 'C'). This retrieves the entire next level in single query.
*/
const children = await db.artifact.findMany({
where: {
parentArtifactId: { in: currentLevelIds },
deletedAt: null,
},
select: { id: true },
});
// No children means we've reached the leaf level, so the traversal is complete.
if (children.length === 0) break;
// Extract the child IDs from the query result. These IDs are added to the final list of descendants for that level and also become the parent IDs for the next BFS iteration, allowing the traversal to continue level by level.
const childIds = children.map((child) => child.id);
// Record every descendant discovered at the current level.
descendantIds.push(...childIds);
// Move one level deeper in the tree. The children from this iteration become the parents searched in the next.
currentLevelIds = childIds;
}
// Return all descendants in breadth-first order.
return descendantIds;
}Why this is powerful: If a tree has 1,000 nodes but only 4 levels of depth, this code executes exactly 4 database queries, not 1,000.
#Under the Hood: Raw BFS Optimizations
To truly own this optimization, it helps to understand how BFS works at a fundamental level. While implementing a raw BFS in TypeScript, I focused on two critical performance details that are often overlooked in beginner tutorials.
function bfs(graph: Record<string, string[]>, start: string): void {
/*
- Stores every node we've already visited. Without this, a graph containing cycles (e.g. A -> B -> A) would cause us to visit the same nodes forever.
- The Set allows O(1) lookup when checking whether a node
has already been processed.
*/
const visited = new Set<string>();
// The BFS queue. BFS explores nodes level by level, so the first node discovered should also be the first node processed (FIFO - First In, First Out). We begin by placing the starting node into the queue.
const queue: string[] = [start];
// Instead of calling queue.shift(), which is O(n) because every remaining element must be moved left, we keep an index pointing to the current front of the queue. This makes dequeue operations O(1).
let front = 0;
// Mark the starting node as visited immediately after enqueueing it. Marking it now prevents the same node from being added to the queue multiple times if another node points back to it.
visited.add(start);
// Continue until there are no more nodes left to process. The queue may continue growing as we discover new neighbors, so we stop only when the front pointer reaches the end.
while (front < queue.length) {
// Remove the next node from the logical front of the queue. Using front++ simply advances our pointer instead of physically removing the element from the array.
const node = queue[front++];
// Visit (process) the current node.
console.log(node);
// Look at every node directly connected to the current node. Since BFS visits nodes level by level, every neighbor discovered here belongs to the next level of the traversal.
for (const neighbor of graph[node]) {
/*
- Ignore neighbors we've already seen. If this node hasn't been visited before, we:
1. Mark it as visited.
2. Add it to the end of the queue.
- It will eventually be processed after all previously discovered nodes have been processed.
*/
if (!visited.has(neighbor)) {
visited.add(neighbor);
queue.push(neighbor);
}
}
}
}
// Adjacency List representation of the graph.
const graph: Record<string, string[]> = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "F"],
D: ["B"],
E: ["B", "F"],
F: ["C", "E"],
};
// Start the traversal from node "A".
bfs(graph, "A");Two Key Takeaways from the Raw Implementation:
-
The
visitedSet for Cycle Prevention: Even though artifact trees shouldn’t have cycles, real-world data can be messy. Using aSetensures O(1) time complexity for lookups, preventing infinite loops if a graph contains cyclic references (e.g., A → B → A). -
The front Pointer for O(1) Dequeues: Many developers implement BFS queues using
queue.shift(). However, in JavaScript,shift()is an O(n) operation because every remaining element in the array must be shifted left by one index. By using a simplefrontinteger pointer (queue[front++]), we achieve a logical dequeue in O(1) time, avoiding unnecessary memory reallocation.
#Why This Matters: Building for Scale
As a software engineering student transitioning from building tutorial-style projects to engineering robust systems at scale, paying attention to these details is crucial.
- Database Efficiency: Batching queries by tree level instead of per node is a fundamental pattern for handling hierarchical data (comments, categories, organizational charts).
- Algorithmic Awareness: Knowing why
queue.shift()is dangerous in a tight loop, and how to fix it with a pointer, demonstrates a deeper understanding of how JavaScript engines handle memory and arrays. - Defensive Programming: Including a
visitedset and checking fordeletedAt: nullensures the system remains resilient even if data integrity is compromised.
Optimizing cascading soft deletes isn’t just about writing a loop; it’s about understanding the shape of your data and the cost of your operations. By combining a level-by-level BFS strategy with Prisma’s
INclause, we can turn an O(N) database nightmare into an O(Depth) dream.
Have you faced similar challenges with hierarchical data? I’d love to hear how you’ve optimized tree traversals in your projects! Let’s connect and discuss