Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A MongoDB collection of user activity documents, each with an embedded events array that grows with every click, has become slow to update and some writes fail. Explain what is happening and how you would remodel it.

Each activity document has an events array that grows on every click, so documents keep getting bigger: every update writes a larger document, the multikey index on the array gains an entry per event, every read pulls the whole history into memory and over the network, and once a document reaches MongoDB's 16 MB limit the update fails. The fix is to bound the documents, either with the bucket pattern, one document per user per day or per 200 events with a count field, or with one document per event indexed on (userId, timestamp), possibly in a time-series collection, migrated with dual writes and a backfill before readers switch.

Why this question is asked

Unbounded arrays are the most common modelling mistake in document databases, and they fail slowly. On day one the design looks elegant: one document per user, with all their activity inside. Months later the heaviest users have documents of several megabytes, updates are slow, memory is full of data nobody reads, and some writes start failing. Interviewers like this question because it tests whether we understand what the database does on every update, not just how the data looks. In this answer, we will reproduce the problem, explain what happens inside the database, and then compare two remodels, the bucket pattern and one document per event, before planning a safe migration.

1Reproducing the Problem

The current model looks like this. Every click appends one element to the events array of the user's document with $push.

Java
// One document per user, an array that grows forever
db.user_activity.updateOne(
{ _id: 42 },
{ $push: { events: { type: "click", page: "/cart", at: new Date() } } },
{ upsert: true });
db.user_activity.createIndex({ "events.at": 1 }); // multikey: one entry per event
Object.bsonsize(db.user_activity.findOne({ _id: 42 })); // 9,830,412 bytes after 8 months
// a few months later, for the heaviest users, the update fails:
// the resulting document would exceed the 16 MB BSON document limit

Notice that nothing in this code limits the array. A light user may have a few hundred events, but an automated client or a very active user can produce tens of thousands per day, and those are exactly the documents that break first. Check your version for the exact error text; the cause is always the 16 MB maximum document size.

2What Happens on Every Update and Read

MongoDB's storage engine, WiredTiger, does not edit a document in place. When we push one small event, it writes a new version of the whole document into its cache and eventually to disk, and the journal and the replication log record the change too. So the cost of appending 100 bytes grows with the size of the document: at 10 MB we are rewriting megabytes to add a click. Older MongoDB versions with the MMAPv1 engine had a similar problem in another form, moving documents that outgrew their space on disk.

The index makes it worse. An index on events.at is multikey, which means it holds one entry per array element. A user with 200,000 events contributes 200,000 index entries, and the index for the whole collection grows far beyond what fits in memory. Reads suffer as well: to show the last ten events, the server loads the whole document into its cache, even if a $slice projection sends only ten events over the network. Big documents push useful data out of the cache, so the whole collection gets slower, not only the heavy users.

Cost as one user's document grows
Events in arrayDocument sizeIndex entriesEffect
1,000about 100 KB1,000fast
50,000about 5 MB50,000slow updates, cache pressure
160,000+near 16 MB160,000+updates fail
Rough figures for events of about 100 bytes each.

3Remodel 1: The Bucket Pattern

The bucket pattern keeps the idea of grouping events but caps each group. We store one document per user per time window, here per day, and also cap it at 200 events with a count field. When a bucket is full, the next event starts a new one.

Java
db.activity_buckets.createIndex({ userId: 1, day: 1, count: 1 });
db.activity_buckets.updateOne(
{ userId: 42, day: "2026-11-06", count: { $lt: 200 } }, // a bucket with room
{ $push: { events: { type: "click", page: "/cart", at: new Date() } },
$inc: { count: 1 },
$setOnInsert: { firstAt: new Date() } },
{ upsert: true }); // no bucket with room -> a new bucket is created
// Latest events for user 42: read the newest bucket or two, not months of history
db.activity_buckets.find({ userId: 42 }).sort({ day: -1, firstAt: -1 }).limit(2);

Notice that the filter includes count less than 200. When today's bucket is full, no document matches, so the upsert inserts a fresh bucket. Every document now stays below about 20 KB, updates stay cheap, and the index has one entry per bucket instead of one per event. The bucket also gives a natural place for small summaries, such as the number of clicks that day.

4Remodel 2: One Document per Event

The other option is to stop grouping and store each event as its own small document with an index on userId and the timestamp. Reads of the latest events become an index range scan, and writes are plain inserts, which are the cheapest operation a document store has. Since MongoDB 5.0 there are also time-series collections, created with a timeField and a metaField, which store such measurements in compressed internal buckets for us, so we get the efficiency of the bucket pattern without writing it ourselves.

Which to choose depends on how the data is read. If we usually read a user's activity per day, buckets fit well. If we query events across users, by type or time range, or want automatic expiry with a TTL, individual documents or a time-series collection are simpler. Either way, every document is now bounded.

Java
db.createCollection("activity_events", {
timeseries: { timeField: "at", metaField: "userId", granularity: "seconds" },
expireAfterSeconds: 60 * 60 * 24 * 90 // keep 90 days
});
db.activity_events.insertOne({ userId: 42, at: new Date(), type: "click", page: "/cart" });

5Migrating Without Downtime

We cannot stop the service to reshape millions of documents, so we migrate in phases. First, the application writes every new event to both the old array and the new collection; this is dual writing. Second, a backfill job reads the old documents user by user and writes their history into the new model, marking each user as done so the job can resume after a failure. Third, we compare counts per user between old and new to check the backfill. Then we switch readers to the new model, behind a feature flag so we can switch back, and only when reads have been stable for a while do we stop writing the array and remove the old documents. For the heaviest users, whose updates already fail, we can start dual writes and backfill first, because the old model is already losing their events.

Step throughMoving from the growing array to bounded documents
  1. Dual write new eventsold array and new collection
  2. Backfill history per userresumable, mark users done
  3. Do counts match per user?
    YesSwitch readers behind a flagNoFix and rerun backfill
  4. Stop old writes, drop old documentsafter reads are stable

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

Could we just trim the array with $slice on every push?

Yes, $push with $each and $slice keeps only the last N events, for example the last 500, which makes the document bounded. It works when we only ever need recent events. But it throws history away, and it still rewrites a document of a few hundred events on every click, so for full activity history the bucket pattern or a separate collection is better.

How do you find which documents are too large?

We can run an aggregation that computes $bsonSize for documents and sorts by it, or sample the collection, and we watch metrics such as average object size, cache usage and the slow query log. A sudden rise in average document size or slow updates on one collection is usually the first sign of an unbounded array.

Does the same problem exist in relational databases?

In a different form. A JSON column that keeps growing has the same rewrite cost, because PostgreSQL writes a new row version for every update, including the whole jsonb value. The relational habit of one row per event naturally avoids it.

7Conclusion

In this answer, we saw that an events array that grows on every click makes documents larger with each update. WiredTiger rewrites the whole document for every change, the multikey index gains one entry per event, every read loads the whole history into the cache, and finally writes fail at the 16 MB limit. We remodel with bounded documents, buckets per user per day or per 200 events, or one document per event in an indexed or time-series collection, and migrate with dual writes, a resumable backfill, a count check and a flag-controlled switch of readers.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem is an unbounded array. Each click does a $push into one document per user, so heavy users end up with documents of many megabytes. MongoDB's WiredTiger engine writes a new version of the whole document on each update, so appending a tiny event costs work proportional to the document size, and the multikey index on the events array holds one entry per event, so it grows huge.

Then, if they want more

Every read also loads the whole document into the cache, even when we only show the latest events, which evicts useful data for everyone. Finally, documents hit the 16 MB limit and those updates fail.

I would remodel with the bucket pattern: one document per user per day, capped at around 200 events with a count field, using an upsert whose filter requires count below 200, so a full bucket automatically starts a new one.

Alternatively, each event becomes its own document indexed on userId and timestamp, or goes into a time-series collection with a TTL. To migrate, I would dual write new events to both models, backfill history with a resumable job, compare counts per user, switch readers behind a feature flag, and then remove the old documents.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Redis documentation, MongoDB manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A MongoDB collection of user activity documents, each with an embedded events array that...": https://scrivio-interview-library.netlify.app/databases/nosql-fundamentals/605362d3da/