Understanding Normalized vs. Non-Normalized Cache
In a blogging application, caching plays a crucial role in performance and efficiency. Let’s explore the concepts of normalized and non-normalized cache using blog posts and their authors as an example. Apollo Client’s caching docs explain how its normalized cache works in practice.
Data from Server
Consider this sample data structure fetched from the server, featuring two posts by the same author, “Alice”:
{
"posts": [
{
"id": "1",
"title": "My First Post",
"author": {
"id": "a1",
"name": "Alice"
}
},
{
"id": "2",
"title": "Another Day, Another Post",
"author": {
"id": "a1",
"name": "Alice"
}
}
]
}
Non-Normalized Cache
In a non-normalized cache, data is stored as received, without any alteration. Here’s how it might look:
{
"posts": [
{
"id": "1",
"title": "My First Post",
"author": {
"id": "a1",
"name": "Alice"
}
},
{
"id": "2",
"title": "Another Day, Another Post",
"author": {
"id": "a1",
"name": "Alice"
}
}
]
}
This approach leads to redundancy and inefficiency, particularly when updating shared data like the author’s name.
Normalized Cache
A normalized cache, on the other hand, structures data by unique identifiers, as shown below:
{
"Post": {
"1": {
"id": "1",
"title": "My First Post",
"authorId": "a1"
},
"2": {
"id": "2",
"title": "Another Day, Another Post",
"authorId": "a1"
}
},
"Author": {
"a1": {
"id": "a1",
"name": "Alice"
}
}
}
This method ensures data integrity, avoids redundancy, and is more space-efficient. Relationships are maintained through references like “authorId.”
While normalized caching adds a layer of complexity, particularly in reconstructing data relationships, it offers significant benefits in large-scale applications. Tools like Apollo Client greatly simplify managing these challenges.
