Serialize and Restore Object Graphs Containing Cycles
System DesignModel answerLast updated
Design a cross-language JSON format and matching encoder/decoder that correctly handles circular references, shared subobjects, and hostile inputs.
Serialize and Restore Object Graphs Containing Cycles
Background
Standard JSON serializers crash or loop infinitely when they encounter a cycle. Consider two nodes that each hold a reference to the other:
a = {"name": "Alice"}
b = {"name": "Bob", "partner": a}
a["partner"] = b
A naive recursive encoder follows a → b → a → b → … until the stack overflows. You need a design that handles this gracefully.
Your task
Design a complete serialization and deserialization strategy for object graphs that may contain cycles or shared subobjects. The inputs are rooted object graphs whose values are strings, integers, or dictionaries with string keys. No other types need to be supported.
Your answer should cover:
- Wire format — What does the JSON output look like? Define the schema precisely enough that any language could implement a compatible decoder.
- Encoding algorithm — How do you detect cycles, assign stable IDs that do not depend on memory addresses, prevent infinite recursion, and preserve shared subobjects (i.e., two references to the same dict must decode back to the same object, not two equal copies)?
- Traversal order — Should you use BFS or DFS? Does the choice matter for correctness? Does it matter for determinism or human readability?
- Decoding algorithm — How do you reconstruct cycles and shared references from the flat format?
- Determinism — What must be true for the same graph to always produce the same bytes, across runs and across machines?
- Security and validation — What checks does the decoder need to safely handle malicious or malformed input?
- Complexity — What is the time and space complexity of encoding and decoding?
- Trade-offs — Briefly compare your chosen design with at least one alternative (e.g., inline anchor/alias schemes, type-tagged formats, or lazy reference resolution).
Expected output
A structured prose design plus a reference implementation in Python. Your implementation should pass a round-trip test: after encoding and decoding the a/b example above, result["partner"]["partner"] is result must be True.
Constraints
- Output must be valid JSON parseable by any standards-compliant parser.
- IDs in the output must not be memory addresses or any other process-local value.
- The encoder must not use recursion in a way that fails on a 1 000 000-node linked list.
- The decoder must reject oversized, structurally invalid, or otherwise hostile payloads.
Hints
Hint 1
Cycle detection and shared-object tracking are the same problem: if you record every dict you have already seen, a second encounter means either a cycle or a shared reference — handle both the same way by emitting a reference rather than expanding the object again.
Hint 2
Flatten the graph into an array: each dict gets one slot, its index is its stable ID, and every reference inside an entry becomes {"$ref": n}. This caps JSON nesting depth at a small constant regardless of graph depth, so neither your code nor the JSON parser can stack-overflow.
Hint 3
Decode in two explicit passes: first allocate one empty dict per slot, then fill in the values. Because every target object already exists before any field is resolved, forward references and back-edges (cycles) need no special handling — they are just array lookups.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
1. Requirements and scope
Pin down what needs to be true before choosing a format:
- Values:
str,int, anddictwith string keys. Booleans, floats, lists, andNoneare out of scope; reject them explicitly rather than silently coercing them. - Identity vs. equality: two references to the same dict must decode to one shared object. Two equal but distinct dicts must remain distinct. This is a stricter requirement than most serializers provide.
- Portability: the format must be parseable by any language. Memory addresses (
id()in Python, pointer values in C) must never appear in the output. - Determinism: identical graphs must produce identical bytes on every run and every machine. This enables diffing, hashing, and caching.
- Safety: the decoder must not crash, allocate unbounded memory, or execute arbitrary code when given adversarial input.
- Scale: the encoder must handle graphs with millions of nodes without hitting Python's recursion limit.
2. Wire format: a flat object table
{
"version": 1,
"root": {"$ref": 0},
"objects": [
{"name": "Alice", "partner": {"$ref": 1}},
{"name": "Bob", "partner": {"$ref": 0}}
]
}
Every dict in the graph occupies exactly one slot in the objects array. Its array index is its stable ID. Inside any slot, each value is either an inline primitive (str or int) or a reference {"$ref": n}. The root field points to the entry point, and may itself be a primitive if the root value is not a dict.
This shape has several useful properties. JSON nesting depth is bounded at roughly 4 levels regardless of graph depth, so neither the encoder nor any downstream JSON parser can stack-overflow. The $ref sentinel can never collide with user data because user dicts are never inlined — they always appear as table entries. A user dict that happens to have a key called "$ref" is simply stored as a normal table entry; the $ref form only appears in value positions, not as table entries themselves.
3. Encoding
The core insight is that cycle detection and shared-subobject tracking are the same mechanism. Maintain a map from id(obj) to its assigned index. When a dict is encountered:
- If it is new, assign the next index, reserve a slot in the table, and enqueue it for expansion.
- If it has been seen before (whether via a cycle or a second reference), just emit
{"$ref": index}.
Because each dict is expanded exactly once, infinite recursion is structurally impossible.
Use an iterative BFS queue rather than recursion. Recursive DFS fails on chains longer than Python's default recursion limit (~1 000 frames). An explicit BFS queue handles a 1 000 000-node linked list with flat memory usage. Iterative DFS with an explicit stack is equally correct; it assigns IDs in preorder (parents before children), which tends to be more readable, but BFS is simpler to reason about for this use case.
For determinism, sort dictionary keys before encoding them. Emit the final JSON with sort_keys=True and fixed separators. The id() map is only used during encoding, while the original objects remain live, so it is a valid in-process key; it never touches the output.
4. Decoding: two explicit passes
Pass 1 — allocate. Read the objects array and create one empty dict for each entry. At this point no values are filled in.
Pass 2 — fill. Iterate over entries and resolve each value. Primitives are copied in directly. A {"$ref": n} is validated (must be an integer in [0, len(nodes))) and resolved to nodes[n], which already exists from pass 1.
Because all target objects exist before any field is resolved, cycles and forward references are handled identically and need no special-casing.
5. Reference implementation
import json
from collections import deque
MAX_OBJECTS = 1_000_000
MAX_BYTES = 50_000_000
def _is_prim(v):
return isinstance(v, str) or (isinstance(v, int) and not isinstance(v, bool))
def serialize(root) -> str:
index, table, queue = {}, [], deque()
def register(v):
"""Return the JSON-safe representation of v."""
if _is_prim(v):
return v
if isinstance(v, dict):
k = id(v)
if k not in index: # first encounter: assign ID and enqueue
index[k] = len(table)
table.append(None) # reserve the slot
queue.append(v)
return {"$ref": index[k]}
raise TypeError(f"unsupported type: {type(v).__name__}")
out_root = register(root)
while queue: # iterative BFS — no recursion limit risk
d = queue.popleft()
entry = {}
for key in sorted(d): # sorted keys → deterministic output
if not isinstance(key, str):
raise TypeError("dict keys must be strings")
entry[key] = register(d[key])
table[index[id(d)]] = entry
return json.dumps(
{"version": 1, "root": out_root, "objects": table},
sort_keys=True, separators=(",", ":"), ensure_ascii=False
)
def deserialize(text: str):
if len(text) > MAX_BYTES:
raise ValueError("payload too large")
doc = json.loads(text, object_pairs_hook=_reject_duplicate_keys)
if not isinstance(doc, dict) or set(doc) != {"objects", "root", "version"}:
raise ValueError("unexpected envelope shape")
if doc["version"] != 1:
raise ValueError(f"unsupported version: {doc['version']}")
objs = doc["objects"]
if not isinstance(objs, list) or len(objs) > MAX_OBJECTS:
raise ValueError("objects field missing or too large")
nodes = [{} for _ in objs] # pass 1: allocate all targets
def resolve(v):
if _is_prim(v):
return v
if (isinstance(v, dict) and list(v) == ["$ref"] # exactly one key
and type(v["$ref"]) is int # must be int, not bool/float
and 0 <= v["$ref"] < len(nodes)):
return nodes[v["$ref"]]
raise ValueError(f"unrecognisable value: {v!r}")
for node, entry in zip(nodes, objs): # pass 2: fill
if not isinstance(entry, dict):
raise ValueError("each objects entry must be a dict")
for k, v in entry.items():
node[k] = resolve(v)
return resolve(doc["root"])
def _reject_duplicate_keys(pairs):
d = {}
for k, v in pairs:
if k in d:
raise ValueError(f"duplicate JSON key: {k!r}")
d[k] = v
return d
Round-trip test:
a = {"name": "Alice"}
b = {"name": "Bob", "partner": a}
a["partner"] = b
result = deserialize(serialize(a))
assert result["partner"]["partner"] is result # shared identity restored
assert result["name"] == "Alice"
assert result["partner"]["name"] == "Bob"
6. Security and validation
The decoder must be treated as a boundary against hostile input:
- Size and count caps. Reject payloads above 50 MB or more than 1 000 000 objects before allocating anything.
- Strict
$refvalidation. The index must be a Pythonint(notbool, notfloat), and must be in bounds. An out-of-range reference is a crash vector. - Duplicate JSON keys. Different JSON parsers resolve duplicates differently. Reject them outright via the
object_pairs_hook. - No unknown fields. Require exactly the documented envelope keys. Silently ignoring extras creates a hidden extension surface.
- No code execution. Never use type tags that instantiate classes (as
pickleand some YAML profiles do). This format is deliberately data-only. - Optionally, reachability checking. Reject objects not reachable from
root. This prevents payload-smuggling attacks where extra objects are hidden in unreferenced slots.
7. Complexity
| Operation | Time | Space |
|---|---|---|
| Encode | O(N + E) | O(N) |
| Decode | O(N + E) | O(N) |
N is the number of dict nodes; E is the total number of dict-valued fields across all nodes. Each node is visited exactly once in each direction.
8. Trade-offs vs. alternatives
Inline anchor/alias (YAML-style). Objects are nested as normal but annotated with &id on definition and *id on reuse. Output is more readable for shallow graphs. The downside is that JSON depth is proportional to graph depth, so deep graphs overflow any depth-limited parser. Encoding requires either two passes (pre-scan to find shared nodes) or backtracking. This design avoids both problems at the cost of less human-readable output.
Type-tagged formats (e.g., {"__type__": "MyClass", ...}). Useful when the object graph contains heterogeneous types. Introduces a code-execution risk if the decoder reflects on type tags to instantiate classes. The current problem scope is homogeneous (dicts only), so this complexity is unwarranted.
Lazy / streaming decoding. One could resolve $ref values lazily on access rather than in a second pass. This avoids allocating all nodes upfront and supports streaming. The trade-off is significantly more complex decoder logic and the risk of leaving the object graph in a partially filled state if parsing fails midway.
Common mistakes
- Using
id()as the output identifier. It is process-local and non-deterministic across runs. - Using recursive DFS without an iteration cap. A 10 000-node linked list exceeds Python's default recursion limit.
- Not sorting keys before encoding. Output varies based on dict insertion order, breaking determinism.
- Single-pass decoding. Resolving
$refvalues as they are encountered fails for any back-edge or forward reference, which is the exact case this format needs to handle. - Accepting booleans as
$refindices. In Python and JSON,True == 1andFalse == 0, sotype(v["$ref"]) is intis necessary to exclude them.