Why This Matters at Engineering Leadership Scale
The File Collection Size and Top-K Tag Aggregator is a signature Atlassian M60/M70 and staff-level coding drill because it mirrors real production storage billing, media libraries, and compliance document repositories.
At leadership scale, this drill tests read/write trade-offs and data invariants. Scanning a flat array of files on every Top-K read collapses at 2 million files. Worse, the Minute-30 extension - adding nested folders and file deletions - immediately exposes whether you deduplicate overlapping parent/child tags or accidentally double-count bytes across ancestor folders.
Core Mental Model & Architecture
| Strategy | upsertFile / deleteFile | getTotalSize() | getTopK(k) | Space | Best Fit |
|---|---|---|---|---|---|
| Scan all files on read | O(1) | O(F) | O(F * tags + T log T) | O(F) | Prototypes under 1,000 files |
| Incremental Map + Full Sort | O(T_file) | O(1) | O(T log T) | O(F + T) | Moderate tag counts (T < 10k) |
Incremental Map + Size-K Min-Heap | O(T_file) | O(1) | O(T log K) | O(F + T + K) | Large T (100k+), small K |
| Indexed Balanced BST | O(T_file * log T) | O(1) | O(K) | O(F + T) | Extreme read-heavy dashboards |
(F = total files, T = unique tags/collections, T_file = effective tags plus ancestors for one file.)
The core invariant: each file's size counts once in totalBytes and at most once per unique effective collection (direct + ancestors). Computing effectiveCollections: Set<string> on write prevents double-counting when a file is tagged with both finance/q4 and finance, and storing that set on each file makes updates and deletes exact inverses.
Step-by-Step Implementation Tutorial
1. Implement the Compact Min-Heap and Incremental Aggregator (Minutes 5 to 28)
export interface FileRecord { id: string; sizeBytes: number; collections: string[]; }
export interface CollectionSize { collectionId: string; totalBytes: number; }
interface StoredFile { sizeBytes: number; effectiveCollections: Set<string>; }
class MinHeap<T> {
private readonly items: T[] = [];
constructor(private readonly cmp: (a: T, b: T) => number) {}
public size(): number { return this.items.length; }
public peek(): T | undefined { return this.items[0]; }
public push(item: T): void {
this.items.push(item);
let i = this.items.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(this.items[i], this.items[p]) >= 0) break;
[this.items[i], this.items[p]] = [this.items[p], this.items[i]];
i = p;
}
}
public pop(): T | undefined {
if (!this.items.length) return undefined;
const top = this.items[0];
const last = this.items.pop()!;
if (this.items.length) {
this.items[0] = last;
let i = 0;
while (true) {
let s = i;
const l = 2 * i + 1, r = 2 * i + 2;
if (l < this.items.length && this.cmp(this.items[l], this.items[s]) < 0) s = l;
if (r < this.items.length && this.cmp(this.items[r], this.items[s]) < 0) s = r;
if (s === i) break;
[this.items[i], this.items[s]] = [this.items[s], this.items[i]];
i = s;
}
}
return top;
}
public toSortedDesc(): T[] {
return [...this.items].sort((a, b) => this.cmp(b, a));
}
}
export class FileCollectionAggregator {
private totalBytes = 0;
private readonly files = new Map<string, StoredFile>();
private readonly collectionBytes = new Map<string, number>();
// Minute-30 Extension: Nested folder parent lookup
private readonly parentOf = new Map<string, string>();
public setCollectionParent(childId: string, parentId: string): void {
if (childId === parentId) throw new Error("Collection cannot be its own parent");
for (let cur: string | undefined = parentId; cur !== undefined; cur = this.parentOf.get(cur)) {
if (cur === childId) throw new Error(`Cycle detected linking ${childId} -> ${parentId}`);
}
this.parentOf.set(childId, parentId);
}
public upsertFile(file: FileRecord): void {
if (!file.id || file.sizeBytes < 0) throw new Error("Invalid file id or sizeBytes");
if (this.files.has(file.id)) this.deleteFile(file.id);
const effective = this.expandWithAncestors(file.collections);
this.files.set(file.id, { sizeBytes: file.sizeBytes, effectiveCollections: effective });
this.totalBytes += file.sizeBytes;
for (const col of effective) {
this.collectionBytes.set(col, (this.collectionBytes.get(col) ?? 0) + file.sizeBytes);
}
}
// Minute-30 Extension: Safe deletion subtracting cached effective collections
public deleteFile(fileId: string): boolean {
const existing = this.files.get(fileId);
if (!existing) return false;
this.totalBytes -= existing.sizeBytes;
for (const col of existing.effectiveCollections) {
const next = (this.collectionBytes.get(col) ?? 0) - existing.sizeBytes;
if (next <= 0) this.collectionBytes.delete(col);
else this.collectionBytes.set(col, next);
}
this.files.delete(fileId);
return true;
}
public getTotalSize(): number { return this.totalBytes; }
public getTopKCollections(k: number): CollectionSize[] {
if (k <= 0) return [];
const cmp = (a: CollectionSize, b: CollectionSize) =>
a.totalBytes !== b.totalBytes ? a.totalBytes - b.totalBytes : b.collectionId.localeCompare(a.collectionId);
const heap = new MinHeap<CollectionSize>(cmp);
for (const [collectionId, totalBytes] of this.collectionBytes.entries()) {
const entry = { collectionId, totalBytes };
if (heap.size() < k) heap.push(entry);
else if (cmp(entry, heap.peek()!) > 0) { heap.pop(); heap.push(entry); }
}
return heap.toSortedDesc();
}
private expandWithAncestors(direct: string[]): Set<string> {
const unique = new Set<string>();
for (const col of direct) {
for (let cur: string | undefined = col; cur !== undefined && !unique.has(cur); cur = this.parentOf.get(cur)) {
unique.add(cur);
}
}
return unique;
}
}2. Write Focused Unit Tests & Minute-30 Extension Checks (Minutes 30 to 50)
Verify four edge cases:
- Shared-tag deduplication: Link
q4->finance; upsertreport.pdf(500 bytes) with["q4", "finance"]. Assertfinanceequals 500 bytes, not 1,000. - Idempotent updates and deletes: Update
report.pdfto 800 bytes and removeq4; asserttotalBytes === 800,q4is evicted fromcollectionBytes, andfinance === 800. - Cycle rejection: Linking
finance->q4throws a cycle error before mutatingparentOf. - Deterministic Top-K tie-breaking: Equal-size collections return in stable lexicographical order.
Worked Production Scenario: Before vs. After
Context: A document management SaaS (40 enterprise tenants, 12M files, 85k nested tags) computed its Admin Top-10 Storage Dashboard via an unindexed recursive SQL query on read. Without DISTINCT file_id, nested folder rollups inflated parent folder billing totals by up to 38%, causing 19 billing escalations per quarter.
After: The Storage squad moved totals to an incremental rollup table driven by the exact upsertFile/deleteFile effective-set delta pattern and bounded heap selection.
| Metric | Before | After |
|---|---|---|
| Top-10 Dashboard p95 latency | 8.4 seconds (frequent 504s) | 22 milliseconds |
| Parent folder billing double-count error | Up to +38% inflated | 0% (exact reconciliation) |
| Database CPU during Monday logins | 88% saturation | 9% steady |
| Billing support escalations / quarter | 19 | 0 |
Common Failure Modes & Anti-Patterns
- Iterating raw tag arrays directly: Counts duplicate tags (
["hr", "hr"]) and overlapping parent/child tags twice. Fix: Normalize every file throughexpandWithAncestors()into aSet<string>. - Skipping folder cycle validation: An accidental
A -> B -> Alink hangsexpandWithAncestors()forever. Fix: Validate ancestor chains insidesetCollectionParent()and stop onunique.has(cur). - Leaving zero-byte tags in
collectionBytes: Inflates heap/map size and pollutes Top-K output with empty collections. Fix: Delete keys once their total reaches<= 0.
How to Handle Pushback in the Room
Skeptical Principal Engineer: "Why write a Min-Heap when Array.from(map).sort().slice(0, k) is two lines?"
Calm Response: "Under a few thousand tags, .sort().slice(0, k) is simpler and fine - I would call that out explicitly. Once tenants reach 100k tags asking for Top 10 on every page load, a size-K min-heap avoids sorting 100k entries and drops complexity from O(T log T) to O(T log K)."
Pushing Product Manager: "Can we allow reparenting folders holding millions of files synchronously on button click?"
Calm Response: "Reparenting a populated folder changes effective ancestor sets across the entire subtree. Running an async delta-recalculation job keeps the HTTP request instant while updating live rollup counters accurately."
Key Takeaways & This Week's Action Rep
- Maintain incremental aggregates on write: Keep
getTotalSize()O(1)and dashboard reads predictable at scale. - Deduplicate direct + ancestor tags in a
Set: Eliminates duplicate-tag and nested-folder double-counting structurally. - Store per-file effective snapshots: Makes
upsertFileanddeleteFileexact inverses. - Use
O(T log K)min-heaps with deterministic tie-breakers: Keeps Top-K fast and unit tests stable.
This Week's Action Rep: Set a 45-minute timer with AI autocomplete off. Build FileCollectionAggregator, add nested folders + deleteFile at minute 30, and assert a file tagged with both a child and parent folder counts exactly once.