<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sandeep Nair on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Nair on Medium]]></description>
        <link>https://medium.com/@sandipsnair?source=rss-ad2c45ff9981------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aJ6JTF21nyw-lc5dSx5UdA.jpeg</url>
            <title>Stories by Sandeep Nair on Medium</title>
            <link>https://medium.com/@sandipsnair?source=rss-ad2c45ff9981------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 02:04:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandipsnair/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Every Large MongoDB Migration Needs RRR: Resilient, Resumable, and Reporting]]></title>
            <link>https://medium.com/@sandipsnair/rrr-what-does-it-stand-for-c5fe05cda0d5?source=rss-ad2c45ff9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5fe05cda0d5</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[resilience]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[azure-documentdb]]></category>
            <dc:creator><![CDATA[Sandeep Nair]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 05:34:31 GMT</pubDate>
            <atom:updated>2026-07-24T04:49:16.519Z</atom:updated>
            <content:encoded><![CDATA[<p>If you ask someone in sustainability, RRR means <strong>Reduce, Reuse, Recycle</strong>.</p><p>If you ask a Bollywood fan, RRR probably means the movie.</p><p>But in a MongoDB to <a href="https://learn.microsoft.com/en-us/azure/documentdb/overview">Azure DocumentDB</a> migration, RRR needs a different expansion:</p><p><strong>Resilient. Resumable. Reporting.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jPSIM_n9uOAh7nz4Giglw.png" /></figure><p>Those three words sound simple, but they decide whether a migration tool survives the real world.</p><p>Moving live MongoDB workloads into Azure DocumentDB, the MongoDB-compatible API, is rarely a one-shot copy. Real datasets are large. Networks drop. Source clusters keep changing while the copy is running. Target services throttle. Indexes take time. Some records are messy. Some failures are temporary. Some are not.</p><p>A migration tool that assumes the happy path will look fine in a demo and fail in production. A tool built around the three R’s behaves differently. It expects trouble, saves its place, and tells the user exactly what happened.</p><p>This post is about those three R’s, and why they matter.</p><h3>R1: Resilient</h3><p>The first mistake is treating transient errors as surprises.</p><p>During a large migration, transient failures are normal. A connection drops. A request times out. The target throttles for a few seconds. A source collection has lock contention. A batch that usually finishes quickly suddenly stalls because the cluster is busy.</p><p>None of those should fail the whole migration.</p><p>Resilience starts with a simple rule: retry the errors that are likely to heal, and stop on the errors that are not.</p><p>That means the tool has to classify failures. A timeout, temporary throttling response, network reset, or short-lived contention event is usually retryable. A schema mismatch, invalid document shape, unsupported value, authentication failure, or permission issue is not going to become correct because we tried it ten more times.</p><p>Retrying everything is not resilience. It is noise.</p><p>The retry loop also needs discipline: exponential backoff, a capped maximum delay, and a bounded number of attempts. If the target is already struggling, immediate retries only make things worse. A good retry policy gives the system time to recover without letting the migration spin forever.</p><p>The tool also has to understand benign duplicates. In a resumed or re-run batch, some records may already exist on the target. If the record landed during an earlier attempt, the correct outcome is often <strong>skipped</strong>, not <strong>failed</strong>. Counting it as a failure creates false alarms and hides the real problem. So the counters matter:</p><ul><li>Processed means the record was copied or applied.</li><li>Skipped means the record was already present or otherwise benign.</li><li>Failed means user attention is required.</li></ul><p>Those are not the same thing.</p><p>Resilience also means shrinking the blast radius when a batch is too large. If a large batch times out repeatedly, trying the same batch again may never help. Split it into smaller sub-batches and retry those. Maybe most records are fine. Maybe the target can handle 500 writes at a time, but not 5,000. Adaptive splitting lets the migration keep moving instead of treating one oversized unit as a wall.</p><p>The same idea applies at collection scale. Large collections should be partitioned into independent chunks so a failure in one chunk does not jeopardize the others. Completed chunks stay complete. Failed chunks can be retried, split, or investigated without restarting the entire collection.</p><p>For live migrations, resilience has one more important place: change capture.</p><p>Starting a stream from the source is not always instant. Establishing a reliable starting point can hit the same transient failures as any other operation. The stream bootstrap itself needs retry logic. Otherwise the tool can survive the bulk copy but fail before continuous sync even begins.</p><p>That is the first R: expect temporary failures, classify them correctly, retry with restraint, and reduce the size of the work when the work is too big to survive.</p><h3>R2: Resumable</h3><p>Resilience handles the failures that heal.</p><p>Resumability handles the failures that do not.</p><p>Sometimes the right answer is not “try again.” The target may be missing an index. A document may violate a constraint. A user may need to fix credentials, increase capacity, or change a setting. The tool should pause cleanly, preserve progress, and let the user resume later from where the job stopped.</p><p>A real migration needs a controlled pause. Do not hard-kill work in the middle of a write. Signal the pause, let in-flight work finish at a safe boundary, then stop. A safe boundary might be the end of a batch or the end of a chunk. That avoids half-written state and makes resume logic much simpler.</p><p>Progress cannot live only in memory. It has to survive process restarts, machine failures, planned pauses, and crashes. The state store needs to know where the job is at multiple levels:</p><ul><li>Job level: is the overall migration running, paused, failed, or complete?</li><li>Collection level: which collections are pending, active, or done?</li><li>Chunk level: which ranges have completed, failed, or still need work?</li></ul><p>That granularity is what makes resume efficient. If nine collections are done and one collection failed on one chunk, resume should not rediscover everything. It should skip completed work and pick up at the unfinished unit.</p><p>State writes should be idempotent. Replaying a save operation should not double-count records, corrupt progress, or move a completed chunk backward. Upsert-style updates are useful here: the state store should converge to the correct status even if the same progress event is written more than once.</p><p>The tool should also track explicit completion flags. Resume logic should not infer “done” from a derived count or an empty queue if the stage never actually marked itself complete. Without explicit flags, a resumed job can skip unfinished work because the state looked close enough.</p><p>Live replication needs its own form of resumability.</p><p>For continuous change capture, the tool has to persist a resume marker: an opaque position in the source stream that says, “start from here next time.” If replication runs in both directions, keep separate markers per direction. The marker for source-to-target traffic is not the same as the marker for target-to-source traffic.</p><p>Resume markers can expire, especially after long pauses. The tool needs a fallback. A timestamp-based starting point may be less perfect than an exact stream token, but it is better than losing the ability to resume entirely.</p><p>One subtle bug is late async work. When a job is paused, some in-flight operations may still finish. If those late completions write stale progress after the pause state has been saved, they can overwrite the clean paused state. Guard state writes while paused.</p><p>That is the second R: pause at safe boundaries, persist progress durably, checkpoint at the right granularity, and resume without redoing work that already finished.</p><h3>R3: Reporting</h3><p>The third R is the one users notice first when something goes wrong.</p><p>If a migration fails and the tool only says “error,” it has not helped. The user still has to answer the real questions:</p><ul><li>What failed?</li><li>Which collection or chunk was involved?</li><li>How many times did it retry?</li><li>Was the failure transient or persistent?</li><li>Were records skipped because they already existed?</li><li>Which records still need attention?</li></ul><p>Without reporting, resilience and resumability become invisible. The user cannot trust what they cannot see.</p><p>A good migration tool separates live status from durable logs.</p><p>The live status feed should be lightweight and frequent: percent complete, current phase, records per second, active collection, active chunk, current lag. The durable log should be detailed and structured: severity, timestamp, collection, chunk, operation, retry attempt, error category, backoff applied, batch size, and final outcome.</p><p>Those two streams should not be the same thing. If every progress tick becomes a durable log entry, storage fills with noise. If detailed errors only appear in a transient UI feed, the information disappears when the browser closes.</p><p>Reporting also needs the right counters. Do not blur everything into one “error count.” Report processed, skipped, and failed records separately. A duplicate on resume is not the same as a failed write. A skipped already-existing record may be evidence that resume is working correctly.</p><p>Retries deserve their own context. When a recoverable error happens, capture the unit that failed, the batch size, the attempt number, the backoff delay, and the error category: timeout, throttling, contention, network, or something else. This turns “it was flaky” into something actionable.</p><p>Performance metrics matter too. Read latency, write latency, throughput, and per-collection progress can reveal where the bottleneck is. If read latency is flat but write latency spikes, the target may be throttling. If one collection has very low throughput while others move quickly, the issue may be partitioning, indexes, or document shape.</p><p>For live migration, per-collection telemetry is especially useful: documents migrated, changes applied, duplicates skipped, last-change timestamps, replication lag, verification differences. Those numbers tell the user whether the target is catching up or drifting away.</p><p>And when retries are exhausted, the tool should log detail that helps the user fix the root cause: a small, truncated sample of failed records or identifiers, plus the exact stage and operation.</p><p>That is the third R: show what happened, what the tool did about it, and what still needs human attention.</p><h3>The three R’s work together</h3><p>The important part is that these are not separate features.</p><p>Resilience without resumability can keep trying forever and still leave the user with no clean recovery path.</p><p>Resumability without reporting can pause safely but leave the user guessing why it paused.</p><p>Reporting without resilience produces beautiful logs for a fragile tool.</p><p>The three R’s reinforce each other:</p><ul><li>Resilience keeps the job moving through normal turbulence.</li><li>Resumability gives the job a safe place to stop when turbulence becomes a blocker.</li><li>Reporting tells the user what happened at every step.</li></ul><p>That combination changes the emotional shape of a migration. Instead of “hope the copy finishes,” the user gets a system that expects failure, contains failure, and explains failure.</p><h3>A practical checklist</h3><p>If you are building or evaluating a MongoDB to Azure DocumentDB migration tool, ask these questions:</p><ul><li>Does it classify transient and persistent errors differently?</li><li>Does it retry with exponential backoff, capped delay, and bounded attempts?</li><li>Does it treat already-existing records as skipped when appropriate?</li><li>Can it shrink oversized batches or chunks instead of failing the whole unit?</li><li>Can it pause at safe boundaries and resume without redoing completed work?</li><li>Does it checkpoint at job, collection, and chunk level?</li><li>Does continuous sync persist resume markers, including per-direction markers when needed?</li><li>Does it have a fallback when a resume marker expires?</li><li>Does it separate real-time status from durable diagnostic logs?</li><li>Does it report processed, skipped, and failed counts separately?</li><li>Does it capture retry context and actionable failed-record samples?</li></ul><p>If the answer to those questions is yes, the tool is built for the world migrations actually run in.</p><h3>The point</h3><p>Reduce, Reuse, Recycle is good advice for sustainability.</p><p>For live MongoDB to Azure DocumentDB migrations, the three R’s are different:</p><p><strong>Resilient. Resumable. Reporting.</strong></p><p>A migration goes well when transient failures do not derail it, persistent failures do not erase progress, and users are never left guessing what happened.</p><p>Do that, and a large migration stops feeling like one fragile copy operation.</p><p>It becomes a controlled process: retry what can heal, pause when humans need to intervene, resume from the last safe point, and report enough detail to make every decision clear.</p><p>And controlled, in database migrations, is exactly what you want.</p><p><em>Azure DocumentDB is a MongoDB-compatible database service, built on the </em><a href="https://github.com/documentdb/documentdb"><em>MIT-licensed open-source DocumentDB project</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5fe05cda0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partitioning: The First Key Ingredient of a Large MongoDB Migration]]></title>
            <link>https://medium.com/@sandipsnair/partitioning-the-first-key-ingredient-of-a-large-migration-2ca0dd101916?source=rss-ad2c45ff9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ca0dd101916</guid>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[azure-documentdb]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[partition]]></category>
            <dc:creator><![CDATA[Sandeep Nair]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 05:30:22 GMT</pubDate>
            <atom:updated>2026-07-23T10:53:37.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Partitioning: The First Key Ingredient of a Large Migration</h3><p>How do you eat an elephant?</p><p>One slice at a time.</p><p>True enough. But in a database migration, the real question is: <strong>how do you slice it well?</strong></p><p>A large migration is only as fast as its slowest, most lopsided slice. If ninety-nine workers finish in ten minutes and one unlucky worker spends three hours on a giant range, the migration took three hours. If one range is so wide that counting it times out, copying it puts pressure on memory, or retrying it means redoing half the collection, partitioning has become the bottleneck.</p><p>This post is about moving data from MongoDB into <a href="https://learn.microsoft.com/en-us/azure/documentdb/overview">Azure DocumentDB</a>, Microsoft’s fully managed, MongoDB-compatible document database service. More specifically, it is about what we learned building a real partitioner for that path: why the obvious solution is not always cheap, why counts can quietly become the enemy, and why a good migrator needs more than one way to slice a collection.</p><h3>Why partitioning matters</h3><p>At small scale, a collection can be copied as one unit of work. Start the copy, wait for it to finish, move on.</p><p>At large scale, that stops working.</p><p>The copy has to be split into smaller units so many workers can run in parallel. I will call each unit a <strong>chunk</strong>: a bounded range of documents, usually expressed as lower and upper _id boundaries, that can be copied, tracked, retried, and marked complete independently.</p><p>That independence is the point. If a worker fails, only one chunk is retried. If you need more throughput, you add workers. If one worker is slow, the rest can keep making progress.</p><p>Bad chunks break that model:</p><ul><li>One huge range dominates runtime while every other worker sits idle.</li><li>A wide range makes counting or copying time out.</li><li>A retry repeats too much work because the unit of failure is too large.</li><li>Progress becomes misleading because “one chunk” no longer means roughly the same amount of work.</li></ul><p>Partitioning is how you turn a giant copy into many small, restartable, measurable pieces. Ten workers only help if the work is actually spread across ten workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyvdCaU-zhjtvnvv0dLy2Q.png" /></figure><h3>The easy choice that is not always cheap</h3><p>The first version of a partitioner usually reaches for $sample.</p><p>It sounds perfect: ask MongoDB for sample _id values, sort them, choose boundaries, and use those boundaries as chunk edges. You do not need to understand the data distribution. Let the database show you a representative slice.</p><p>That works, but only when MongoDB can use the cheap path.</p><p>$sample is fast on the random-cursor path. That path has two important conditions: the requested sample must be less than roughly five percent of the collection, and $sample must not have a $match stage in front of it.</p><p>The obvious $match case is a user filter. If the migration is only copying part of a collection, $sample has to run after that filter.</p><p>The less obvious case is mixed _id BSON types. Suppose 99.9 percent of a collection uses ObjectId, but a small minority uses string _ids. A general sample can easily miss the strings entirely. The majority type hides the minority type, and the partitioner quietly creates boundaries for only part of the collection. To avoid that, each _id type needs its own sampling pass, which means adding a $type filter.</p><p>That filter is also a $match. Once it is present, MongoDB cannot use the random cursor path. It falls back to scanning the matching documents and doing a top-k sort. On a large collection, that is server work you can feel.</p><p>So sampling needs a cost model, not blind faith.</p><p>A raw sample also does not automatically give you equal-sized boundaries. It gives you candidate _ids. If you pick too few candidates, random gaps in the sample can turn into lopsided chunks. When we are on the genuine $sample path, we oversample by 10x: if we need 100 boundaries, we ask for about 1,000 candidate _ids, sort and dedupe them, then quantile-select boundaries from that sorted sample.</p><p>But when there is a $match ahead of $sample, we do not oversample aggressively. We hard-cap the sample size at about 3,000 so the fallback scan-and-sort stays bounded. The partitions may be less perfect, but partitioning itself does not become the incident.</p><p>One practical detail: $sample on a huge collection can still take minutes. We run it with a long MaxTime and retry up to ten times. Partitioning should be patient, but not unbounded.</p><h3>Chunks need guardrails</h3><p>A chunk is not just a boundary. It is the amount of work you are asking one worker to own.</p><p>Too few chunks and you lose parallelism and restartability. Too many chunks and orchestration overhead starts to dominate. The partitioner keeps the count sane with tiered floors: around 100K documents per chunk for small and medium collections, and around 1M documents for very large collections above 100M documents.</p><p>Initial boundaries are still only a first guess. A sampled boundary can land badly. A time-based boundary can cover a bursty insert window. A filtered collection can have records concentrated in one narrow key range.</p><p>So the partitioner inspects the chunks it created. If one is still too large to be a safe unit of work, it recursively splits only that range until the pieces are manageable, or until it reaches a configured safety limit. That turns “one bad boundary” into a recoverable condition instead of forcing the migration to drag one giant chunk behind it.</p><p>Then there is the knob every real migration eventually needs: <strong>Partition factor</strong>.</p><p>Partition factor scales the chunk floor down. At 100%, the default, the partitioner uses the normal floor. At 50%, the effective floor is half as large, producing smaller and more numerous chunks. At 25%, it becomes more aggressive again.</p><p>That helps when you need more parallelism, when _id distribution is uneven, or when narrower ranges make per-chunk counting less likely to time out. Defaults are useful. Knobs are necessary.</p><h3>Counting is the silent killer</h3><p>Sampling gets the attention because it is the clever part. Counting is the part that quietly breaks your plan.</p><p>An unfiltered count can be cheap enough. A filtered count is often a full scan. On some sources, a filtered count over a wide range can take so long that it times out or even resets the connection.</p><p>The partitioner has to design for that failure.</p><p>If a collection is smaller than the minimum chunk floor, do not partition it. Make one chunk and move on.</p><p>If a count times out while deciding how many chunks to create, do not collapse to one giant partition. That is the worst possible fallback because it turns a count problem into a migration runtime problem. Use an estimated count or a previously computed count instead.</p><p>Over-estimating is usually harmless. The count only decides how many chunks to create. If the estimate is high, you create more chunks than strictly necessary. That adds some overhead, but preserves parallelism and restartability. Under-estimating is more dangerous because it creates fewer, larger chunks and pushes the pain downstream.</p><p>A rough count that keeps the plan distributed is better than a precise count that never returns.</p><h3>_id type awareness is not optional</h3><p>In clean examples, every document has an ObjectId _id.</p><p>Real collections are messier. You find ObjectIds, strings, integers, binary values, sometimes even compound shapes depending on source history and application behavior. A partitioner that assumes one _id type can miss records or compare values MongoDB cannot sensibly order together.</p><p>So the partitioner probes each collection for the _id BSON types that actually exist. It partitions by type when it has to, because each type needs its own chance to produce boundaries. If only one type is present, it skips the $type predicate so the pipeline can stay on the cheaper path. If mixed types are present, it filters by $type and accepts the $match cost.</p><p>We also let users provide the expected _id type for a collection. Application teams often know the data shape better than a generic probe can. If they know a collection uses only ObjectId, or only string _ids, the partitioner can treat it as single-type and avoid an unnecessary $type predicate.</p><p>Type awareness is required for correctness. The type predicate should only be paid for when it is needed.</p><h3>ObjectId gives you a second path</h3><p>ObjectId has a useful property: its leading bytes encode a timestamp. It is not a perfect sequence number, but it is roughly monotonic for many write patterns.</p><p>That gives us a cheap partitioning strategy. Instead of sampling documents, find the minimum and maximum ObjectId. Both are indexed operations. Convert those ObjectIds into large integers, step linearly between them, and turn those steps back into ObjectId boundaries.</p><p>No $sample. No collection scan. No top-k sort.</p><p>For large ObjectId-based collections, these <strong>Time Boundaries</strong> are attractive. But time distribution is not record distribution. A steady insert stream may produce balanced time ranges. A bursty backfill may put 80 percent of the data into one narrow time window.</p><p>That is why we added <strong>Adjusted Time Boundaries</strong>. Start with cheap time-based ranges, then validate counts. Merge ranges that are too small. Recursively split ranges that are too large. Use a maximum recursion depth and a dynamic max-records-per-range cap so the partitioner does not chase perfection forever.</p><p>And when counts time out, fall back to splitting the ObjectId range analytically. The result may be less balanced, but it is still distributed, restartable work.</p><h3>There is no single best slicing method</h3><p>The biggest lesson was not that sampling is bad or ObjectId math is good. It was that every strategy is good under the right conditions and expensive under the wrong ones.</p><p>So the partitioner exposes a spectrum:</p><ul><li><strong>Sample Command</strong> for representative boundaries when sampling is affordable.</li><li><strong>Time Boundaries</strong> for cheap ObjectId-based partitioning with no data scan.</li><li><strong>Adjusted Time Boundaries</strong> when you want ObjectId speed plus count-based correction.</li><li><strong>Pagination</strong> when you need deterministic equal-size boundaries using progressive $gt with skip/limit.</li></ul><p>The right answer depends on the collection: _id type, index availability, insert history, filters, size, and how much extra work the source can tolerate during planning.</p><p>A robust migrator does not pretend one method wins everywhere. It lets the strategy match the data shape and degrades gracefully when the ideal path fails.</p><h3>A practical checklist</h3><p>If you are building or tuning partitioning for a large migration:</p><ul><li>Keep the unit of work small enough to retry without drama.</li><li>Avoid one giant fallback partition when counting or sampling fails.</li><li>Detect oversized chunks and recursively split them into manageable ranges.</li><li>Treat $sample as cheap only on the true random-cursor path.</li><li>Cap matched sampling so scan-and-sort work stays bounded.</li><li>Let users provide known _id types, and skip $type filters when they are not needed.</li><li>Use ObjectId structure when you can.</li><li>Make chunk size tunable.</li></ul><h3>The point</h3><p>Partitioning is not just how you make a migration faster. It is how you make it controllable.</p><p>Good slices give you parallelism, restartability, honest progress, and smaller blast radius when something fails. Bad slices turn a large migration into a waiting game where one range, one count, or one overloaded worker quietly decides the schedule.</p><p>So yes, you eat the elephant one slice at a time.</p><p>But the migration succeeds because you learned how to slice it.</p><p>And when the slices are balanced, bounded, and retryable, even a very large migration starts to feel routine.</p><p>And routine, in database migrations, is exactly what you want.</p><p><em>Azure DocumentDB is a MongoDB-compatible database service, built on the </em><a href="https://github.com/documentdb/documentdb"><em>MIT-licensed open-source DocumentDB project</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ca0dd101916" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Proxy That Made a Zero-Downtime MongoDB Migration Reversible]]></title>
            <link>https://medium.com/@sandipsnair/the-proxy-that-made-a-zero-downtime-mongodb-migration-reversible-47b7a4c74118?source=rss-ad2c45ff9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/47b7a4c74118</guid>
            <dc:creator><![CDATA[Sandeep Nair]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 04:33:37 GMT</pubDate>
            <atom:updated>2026-07-16T04:33:37.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Most migration plans have a brave moment in them. The moment you flip the switch, point production at the new database, and hope you sized it right — because going back means another outage, another change window, another apology email.</p><p>That moment is where migrations get scary. Not the copy. The commitment.</p><p>This post is about a small piece of infrastructure that removes the brave moment entirely: a MongoDB wire-protocol <strong>Dual-Write Proxy</strong> (DWP) that lets client apps move from a source MongoDB cluster to <a href="https://learn.microsoft.com/en-us/azure/documentdb/overview">Azure DocumentDB</a> with no coordinated downtime — and, just as importantly, keeps the old cluster live and current <em>after</em> cutover so you can walk it back at any time.</p><h3>The problem it was built to solve</h3><p>Azure DocumentDB speaks the MongoDB wire protocol and BSON, so existing MongoDB apps, drivers, and tools work with little or no change. That makes it a natural migration target. But “the target works” is not the hard part. The hard part is the choreography around it, and three questions show up every single time:</p><ul><li><strong>How do I move a fleet without a synchronized cutover?</strong> You rarely own every app. Getting fifty teams to redeploy at the same instant is a fantasy.</li><li><strong>What happens to in-flight traffic during the flip?</strong> A rolling cutover means, for a few minutes, some apps are on the old cluster and some are on the new one. Do they diverge?</li><li><strong>What if I need to go back?</strong> Once new writes land on DocumentDB, the source starts going stale. An hour later, “roll back” quietly stops being an option.</li></ul><p>You can paper over each of these with runbooks and prayer. The trouble is that a plan held together by prayer is hard to trust, hard to repeat, and hard to hand to a customer team during a change window.</p><p>So the idea was simple: put a transparent seam between the apps and the database, and make <em>which cluster is primary</em> and <em>which way writes replicate</em> into config, not a rebuild.</p><h3>The seam — one proxy, one primary, one optional mirror</h3><p>DWP is a MongoDB wire-protocol-compatible proxy. Clients connect to it exactly as if it were MongoDB — same SCRAM handshake, same reads, same writes. Under the hood it does two things:</p><ul><li><strong>Primary path (synchronous):</strong> every connection is byte-for-byte passed through to a single configured backend, including the client’s own SCRAM. Reads and writes behave exactly as a direct connection would. The proxy never authenticates on the client’s behalf; it forwards the client’s credentials straight to whichever cluster is primary.</li><li><strong>Mirror path (asynchronous, write-only):</strong> on a successful write, the proxy tees the operation into an Azure Blob Storage append-log, and a separate worker drains that log into a second cluster. The mirror lags by a few hundred milliseconds in steady state and never blocks the client.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PS2tsprMBvbpXeEwM2W7UQ.png" /></figure><p>That is the whole trick. Migration becomes a matter of pointing those two arrows through four phases:</p><ol><li><strong>Insert the proxy.</strong> Source MongoDB stays primary, the mirror is off. It is a transparent hop; nothing changes.</li><li><strong>Online migration.</strong> Source stays primary, the mirror is still off, while an external tool seeds DocumentDB from the source.</li><li><strong>Flip and reverse-sync.</strong> DocumentDB becomes primary and the mirror reverses to point back at the source. New writes land on DocumentDB, and the source stays current.</li><li><strong>Retire the source.</strong> DocumentDB is authoritative and the mirror is turned off, because it is no longer needed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95xkJooro2OQyhspWBW8MA.png" /></figure><p>The apps never know any of this happened. They talked to one endpoint the entire time.</p><h3>Scenario 1 — Zero-downtime online migration</h3><p>The first thing DWP buys you is a fleet cutover with no coordinated downtime.</p><p>You insert the proxy first, while the source is still primary. Each app owner swaps their connection string for the proxy’s endpoint on their own schedule — a low-risk change, because the proxy is a pure pass-through at that point. No app has to move on anyone else’s calendar.</p><p>Once every app is behind the proxy, you run your online migration tool of choice to seed DocumentDB from the source. DWP is deliberately <em>not</em> in that path — the copy is done externally, the way copies should be, while the proxy keeps serving live traffic.</p><p>Then comes the flip. And this is where a proxy earns its keep. The cutover is a config change, not a redeploy: the proxy re-reads its runtime configuration and only <strong>new</strong> sessions dial the new primary, while existing sessions keep their socket and drain naturally as clients reconnect. There is no pod restart, so live TCP sessions are never severed. Replicas move to DocumentDB one at a time.</p><p><strong>When to use it:</strong></p><ul><li>Migrating a large fleet of independent apps you cannot cut over in lockstep.</li><li>Any migration where a maintenance window is expensive, contentious, or simply not allowed.</li></ul><p><strong>The benefit:</strong> apps keep running unchanged throughout, and each one moves independently. The interesting parts become the plan and the sequencing, not the outage.</p><h3>Scenario 2 — Keep the source current so you can revert</h3><p>This is the one I would keep even if I had to give up the rest.</p><p>During the flip, the fleet is briefly mixed — some sessions land on DocumentDB, some still land on the source. If new writes only landed on DocumentDB, the source would immediately start to drift, and anything still reading from it would return stale data. Worse, the moment you noticed a problem and wanted to go back, the source would already be behind.</p><p>DWP handles this by reversing the mirror at cutover. The instant DocumentDB becomes primary, every write to it is asynchronously <strong>dual-written back to the source MongoDB</strong>. The old cluster is no longer a fossil you left behind — it is a hot, readable, continuously updated standby.</p><p>That changes the whole emotional shape of a migration. Rollback is no longer an outage; it is a config flip in the other direction. Point the primary back at the source, and because the reverse mirror kept it current, it never fell behind. You lose nothing.</p><p><strong>When to use it:</strong></p><ul><li>High-stakes cutovers where “we can always go back” has to be true, not aspirational.</li><li>Regulated or revenue-critical workloads where an irreversible flip is a non-starter.</li><li>Long bake periods, where you want DocumentDB serving production for days while the source stays warm as insurance.</li></ul><p><strong>The benefit:</strong> the migration is reversible for as long as you want it to be. You decide when to retire the source — on evidence, not on a deadline — and until then, going back costs a config change instead of a recovery project.</p><h3>Scenario 3 — Dual-write for parity and confidence</h3><p>Even outside a one-way migration, the same machinery is useful. Because the proxy mirrors writes into a second cluster, you can run the target alongside the source and compare them under real traffic before you trust it. Parity checking stops being a one-off script and becomes something the plumbing does for you continuously. The mirror preserves per-_id FIFO and resolves concurrent writes to the primary&#39;s commit order — last-writer-wins, exactly as the primary already does — so the trailing cluster does not drift for anything that flows through the proxy.</p><p><strong>When to use it:</strong> evaluation and UAT, where you want the target exercised by production-shaped traffic before anyone commits to it.</p><p><strong>The benefit:</strong> you cut over on measured confidence instead of a leap of faith.</p><h3>How it is packaged</h3><p>DWP runs on Azure Kubernetes Service: the proxy is a load-balanced TCP endpoint on the MongoDB port, and a separate worker drains the blob-log into the secondary. Deploy and cutover are scripts, not surgery — you stage the fleet once, then trigger the flip (and the rollback) with a single command each. It is open source: <a href="https://github.com/sandeepsnairms/AzDocumentDB_Proxy_WithDualWrites">github.com/sandeepsnairms/AzDocumentDB_Proxy_WithDualWrites</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DJOm9Bz3MvL1dfADgEFTQ.png" /></figure><p>A few honest constraints are worth calling out, because they shape the plan:</p><ul><li><strong>Schema and identity are not mirrored.</strong> Collections, indexes, users, passwords, and roles must be pre-provisioned identically on the target before the flip, because the proxy passes the client’s SCRAM straight through — clients re-authenticate against the target the instant it becomes primary.</li><li><strong>The mirror is asynchronous.</strong> Read-after-write against the <em>primary</em> of each phase is always consistent, because reads and writes share the same connection. The trailing cluster is eventually consistent, by design.</li><li><strong>Every mirrored document carries a </strong><strong>__dwp__ bookkeeping field.</strong> The proxy stamps a small reserved __dwp__ subdocument onto each mirrored write — its per-document idempotency and last-writer-wins marker. It is harmless to leave in place, easy to strip once the source is retired, and something any parity check must skip (see below).</li><li><strong>Managed identity end-to-end.</strong> The blob-log transport uses workload identity; the only secret in play is the secondary cluster’s connection string, held in a Kubernetes Secret. No keys on the hot path.</li></ul><p>None of this is exotic. That is the point.</p><h3>Proving the two clusters match</h3><p>Because the trailing cluster is eventually consistent, in every scenario you eventually need to prove the two clusters actually match. Pair the proxy with a validation pass like the <a href="https://medium.com/@sandipsnair/three-small-tools-that-made-a-mongodb-to-documentdb-migration-feel-boring-4ea85fe917dc">Collection Comparer</a>, which diffs source and target collections document-by-document.</p><p>One thing to configure there: the proxy stamps a reserved __dwp__ bookkeeping field onto every mirrored document — its per-document idempotency and last-writer-wins marker. Tell the Comparer to <strong>exclude </strong><strong>__dwp__</strong> from the hash comparison; it exposes a skip-fields option for exactly this. Otherwise every mirrored document reads as a mismatch.</p><h3>The point</h3><p>A migration goes well when the scary moment is engineered out of it — when the flip is a config change you can undo, and the cluster you are leaving stays alive long enough to prove you do not need it anymore.</p><p>That is all DWP really does. It turns “point production at the new database and hope” into “move apps one at a time, keep the old one warm, and decide to retire it when the evidence says so.” The source stays current until <em>you</em> say it is done, and reverting costs a config flip instead of an incident.</p><p>Do that, and a migration stops being a brave moment. It becomes routine.</p><p>And routine, in database migrations, is exactly what you want.</p><p><em>The Dual-Write Proxy is open source: </em><a href="https://github.com/sandeepsnairms/AzDocumentDB_Proxy_WithDualWrites"><em>github.com/sandeepsnairms/AzDocumentDB_Proxy_WithDualWrites</em></a><em>. Azure DocumentDB is a MongoDB-compatible database service, built on the </em><a href="https://github.com/documentdb/documentdb"><em>MIT-licensed open-source DocumentDB project</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b7a4c74118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three Small Tools That Made a MongoDB to DocumentDB Migration Feel Boring]]></title>
            <link>https://medium.com/@sandipsnair/three-small-tools-that-made-a-mongodb-to-documentdb-migration-feel-boring-4ea85fe917dc?source=rss-ad2c45ff9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ea85fe917dc</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[azure-documentdb]]></category>
            <dc:creator><![CDATA[Sandeep Nair]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 03:43:46 GMT</pubDate>
            <atom:updated>2026-07-24T04:52:46.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Migrating a database is rarely the hard part. Trusting the migration is.</p><p>You can move bytes from one cluster to another and still not know the answer to the only question that matters at cutover: is the target actually a faithful copy of the source, and can it take the load the source used to take?</p><p>That gap — between “the data moved” and “I can prove the data moved correctly” — is where migrations get stressful. It is also where I kept reaching for the same small utilities over and over. Eventually I stopped rebuilding them per engagement and turned them into a single application: <a href="https://github.com/sandeepsnairms/mongodb_migration_helper_tools">mongodb_migration_helper_tools</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfv-ZHIdBnvocFhpeyV-9w.png" /></figure><p>This post is about why those tools exist, who they are for, and when to reach for each one.</p><h3>The problem they were built to solve</h3><p><a href="https://learn.microsoft.com/en-us/azure/documentdb/overview">Azure DocumentDB</a> is a fully managed, MongoDB-compatible document database. Because it speaks the MongoDB wire protocol and BSON, existing MongoDB applications, drivers, and tools work with little or no change. That compatibility makes moving an existing MongoDB workload to DocumentDB a common path.</p><p>But “common path” does not mean “no questions.” When you plan a migration, three questions show up every single time:</p><ul><li>How hard is the source actually working? What does its change stream throughput really look like before I touch anything?</li><li>Is the online sync actually flowing? If the source is quiet, how do I generate change-stream traffic to prove CDC is being captured and replayed on the target?</li><li>Did the data land intact? After the copy, does the target match the source, and is any difference just replication lag or real drift?</li></ul><p>You can answer all three by hand. I did, for a while — a script here, a one-off comparison there. The trouble is that ad-hoc answers are hard to trust, hard to repeat, and hard to hand to a customer team during UAT.</p><p>So the motivation was simple: turn the three recurring questions into three repeatable tools, put them behind one login, and make them easy to run from anywhere.</p><h3>Change Stream Monitor — understand the source before you move it</h3><p>The first mistake in a migration is guessing at the workload.</p><p>Before you provision a target or size a migration job, you want to know what the source is doing right now. How many changes per second flow through it? Which collections are hot? What is the peak, not just the average?</p><p>The Change Stream Monitor watches MongoDB change streams in real time and answers exactly that. You point it at a collection, a database, or the whole cluster. It reports live TPS, changes per minute, and a per-collection breakdown with change counts, current TPS, and max TPS. At cluster scope you can filter to just the db.collection namespaces you care about, so the noise from dead collections does not drown out the signal.</p><p><strong>When to use it:</strong></p><ul><li>Early, during assessment, to profile the source workload and set realistic expectations for the migration window.</li><li>During the migration itself, to benchmark change stream read speed and confirm the source is behaving the way your plan assumed.</li></ul><p><strong>The benefit:</strong> every downstream decision — job count, target sizing, cutover timing — comes from measured throughput instead of a guess. Resume token support means you can stop and continue from a known point rather than starting over.</p><h3>Change Stream Generator — create the CDC traffic your test needs</h3><p>Here is a problem that surprises people. To validate an online migration, you need the source to be changing — inserts, updates, and deletes flowing through the change stream so the CDC pipeline has something to capture and replay on the target. But a test or staging source is often idle. There is no application hammering it, no steady stream of edits. Without change activity, there is nothing to prove.</p><p>The Change Stream Generator solves that by manufacturing realistic change traffic on demand. It drives configurable, multi-threaded operations: inserts, updates, deletes, or any combination. You control the thread count (1–50), batch size (1–1000), document size, and whether it runs for a fixed number of loops or continuously until you stop it. It can spread writes across random databases and collections, or hit an explicit list of namespaces. For sharded collections, it can attach a shard key with a configurable field, prefix, and value range.</p><p>That flexibility matters because the traffic you generate should resemble the workload you are migrating. A single collection getting uniform inserts exercises very little of the pipeline. A realistic mix of operations across many collections, at production-shaped concurrency, actually tests whether CDC keeps up.</p><p><strong>When to use it:</strong></p><ul><li>During online-sync testing, when the source has no continuous edits of its own and you need change-stream traffic to verify CDC is being captured and replayed.</li><li>To exercise the CDC pipeline end to end and confirm changes land on the target under real volume and concurrency.</li><li>To seed a populated environment on demand when you need data to rehearse against.</li></ul><p><strong>The benefit:</strong> you can validate online migration even against an idle source, instead of waiting for someone to generate traffic by hand or discovering CDC gaps only after real traffic arrives.</p><h3>Collection Comparer — prove the data actually matches</h3><p>This is the tool I would keep even if I had to give up the other two.</p><p>After a migration, the question is never “did it run?” It is “did it copy everything correctly?” The Collection Comparer answers that by sampling documents from the source and target and comparing their hashes. You give it a list of db.collection namespaces, a sample size per collection (1–10,000), and how many collections to compare in parallel (1–32). It reports per-collection document counts, mismatch counts, and status, with expandable error detail.</p><p>The clever part is lag handling. In an online migration, source and target are moving targets — a “mismatch” might just be a document that has not replicated yet. So you can name timestamp fields to sort by most-recent documents and see how far the target lags UTC. Set a lag threshold, and the tool can automatically recheck mismatches above it after the first pass. What remains after the recheck is real drift, not timing noise. Results copy out as HTML or CSV, with filters for mismatches-only, so you can drop a clean report straight into a sign-off.</p><p><strong>When to use it:</strong></p><ul><li>After bulk load, to validate consistency before you trust the target.</li><li>During online sync, to distinguish replication lag from genuine data drift.</li><li>At cutover sign-off, to produce evidence — not a feeling — that the migration is complete.</li></ul><p><strong>The benefit:</strong> you replace “I think it copied” with a report you can show a customer.</p><h3>Who these tools are for</h3><p>If you are planning or executing a MongoDB-to-DocumentDB migration — as a customer team, a partner, or a field engineer — these are for you. They are deliberately small and focused. They do not orchestrate the migration; that is the migration service’s job. They surround it with the visibility and validation the migration itself does not give you: profile the source, generate the change traffic your online-sync test needs, and prove the copy.</p><p>They also earn their keep in UAT. The best time to find a tool gap or a bad assumption is while you still have a rehearsal environment and a customer team learning the runbook. Running these three during UAT turns “we hope it works” into “we watched it work.”</p><h3>How it is packaged</h3><p>The application is a Blazor Server app that uses SignalR for live UI updates and the official MongoDB .NET driver underneath. It is built to deploy to Azure Container Apps on Linux with a single PowerShell script — it creates the registry, builds the image in Azure (no local Docker required), and stands up the container app for you. Access is protected by a password stored as a Container Apps secret, never in plaintext on the revision spec, and connection strings are masked in the UI. In local debug builds the password check is bypassed so you can iterate quickly.</p><p>The one hard prerequisite worth calling out: change streams require a replica set. That is a MongoDB requirement, not a tool limitation, but it will stop you fast if you point the monitor or generator at a standalone instance.</p><h3>The point</h3><p>None of these tools is clever. That is intentional.</p><p>A migration goes well when the interesting parts are the plan and the sequencing, not the surprises. The way you get there is by removing uncertainty early: measure the source instead of guessing, generate real change traffic so you can test online sync before it matters, and prove the copy with evidence instead of optimism.</p><p>Do those three things and a large migration starts to feel routine.</p><p>And routine, in database migrations, is exactly what you want.</p><p><em>The tools are open source under the MIT license: </em><a href="https://github.com/sandeepsnairms/mongodb_migration_helper_tools"><em>github.com/sandeepsnairms/mongodb_migration_helper_tools</em></a><em>. Azure DocumentDB is a MongoDB-compatible database service, built on the </em><a href="https://github.com/documentdb/documentdb"><em>MIT-licensed open-source DocumentDB project</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ea85fe917dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[47 TB, 7,000 Collections, and a 48-Hour Window: What We Learned from a Large-Scale Azure DocumentDB…]]></title>
            <link>https://medium.com/@sandipsnair/47-tb-7-000-collections-and-a-48-hour-window-what-we-learned-from-a-large-scale-azure-documentdb-789376a9c98e?source=rss-ad2c45ff9981------2</link>
            <guid isPermaLink="false">https://medium.com/p/789376a9c98e</guid>
            <category><![CDATA[azure-documentdb]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[azure-cosmos-db]]></category>
            <dc:creator><![CDATA[Sandeep Nair]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 05:43:55 GMT</pubDate>
            <atom:updated>2026-07-07T05:43:55.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>47 TB, 7,000 Collections, and a 48-Hour Window: What We Learned from a Large-Scale Azure DocumentDB Migration</h3><p>Migrating a database is rarely just about moving bytes from one place to another.</p><p>At small scale, a migration can feel mechanical: assess the source, provision the target, copy the data, build the indexes, validate, cut over. At large scale, the mechanics are still there, but the real work shifts somewhere else.</p><p>It becomes a question of sequencing.</p><p>What should happen now? What should wait until after the bulk load? Which production-safe defaults help in steady state but slow you down during migration? And where will the system actually start to bend when pushed harder than it has ever been pushed before?</p><p>We saw that clearly in a recent large enterprise migration to Azure DocumentDB.</p><p>The numbers were not subtle: <strong>47 TB of data</strong>, <strong>7,000+ collections</strong>, a source footprint built on a <strong>27-node replica set</strong>, and a production cutover window of <strong>less than 48 hours</strong>. The target, by contrast, was intentionally lean: a <strong>3-node, 16 TB DocumentDB cluster</strong>.</p><p>On paper, that sounds like a story about scale.</p><p>In practice, it became a story about restraint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kj-IPBdqfWFymYLv5G7nJw.png" /></figure><p>The migration worked because the team did not try to optimize for everything at the same time. Instead, they used assessment data to decide what mattered, proved the plan in UAT, tuned the target for ingestion first, and hardened it after the bulk load was complete.</p><h3>Start with the data you do not need to move</h3><p>Large estates accumulate history.</p><p>Some collections are actively queried. Some are technically present but functionally dead. Some contain useful records mixed with old data that no longer matters to the workload.</p><p>In this migration, the source environment had thousands of collections across multiple workloads. Treating all of them as equally important would have been the first mistake.</p><p>So the migration did not start with tooling. It started with assessment.</p><p>The team used assessment data to understand collection sizes, storage distribution, access patterns, and which collections were worth moving at all. Junk collections were dropped from scope entirely. Large collections were filtered to include only the relevant documents.</p><p>That may sound obvious, but it was one of the most important lessons from the project: <strong>the fastest data to migrate is the data you do not migrate</strong>.</p><p>For a 47 TB estate, scope control is not cleanup. It is a performance strategy.</p><h3>Tune for migration first, resilience second</h3><p>High availability and cross-region replication are exactly the kinds of features you want in a production database.</p><p>But during a bulk migration, they can become part of the problem.</p><p>In early test runs, enabling HA and cross-region replicas during ingestion caused write-ahead logs to pile up. As ingestion pushed the system hard, those logs continued to grow. Disk pressure increased. Eventually, the team saw the kind of failure mode every migration team wants to avoid: disk filling during the load.</p><p>That did not mean HA or cross-region replicas were bad ideas. It meant they were the wrong ideas at the wrong moment.</p><p>The team changed the sequence: load the bulk data first, keep HA and cross-region replicas disabled during the heaviest ingestion period, and turn them back on after the bulk load completes.</p><p>This is one of those decisions that feels uncomfortable until you remember the goal. The target state needs to be resilient. But the migration state needs to be optimized for movement.</p><p>A migration is not the steady state. Treating it like one can make the migration slower, more fragile, or both.</p><h3>Indexes are not free during ingestion</h3><p>Indexes are essential for query performance. They are also expensive to build while data is arriving at high speed.</p><p>During testing, non-unique index builds running alongside rapid ingestion pushed CPU and disk utilization hard. The system was doing two heavy things at once: accepting a large volume of writes and trying to maintain structures that would make future reads fast.</p><p>Again, the fix was sequencing.</p><p>The team moved non-unique index creation to <strong>post-ingestion</strong>, built those indexes in <strong>blocking mode</strong>, and paused CDC online sync while the builds ran.</p><p>That separated two different phases of work:</p><ol><li>Move the data quickly.</li><li>Prepare the data for steady-state query performance.</li></ol><p>Trying to optimize for both at the same time looked elegant on paper. In testing, it created unnecessary resource pressure.</p><h3>Do not blindly mirror the source</h3><p>The source footprint was large: 27 nodes, organized as 9 shards with 3 nodes each, holding roughly 40+ TB of data.</p><p>It would have been natural to mirror that shape on the target. Source is sharded, therefore target should be sharded. Large source, large target. Many nodes in, many nodes out.</p><p>But that would have copied topology instead of understanding the workload.</p><p>The team looked at the actual collections and found that no individual collection was too large for one node on the target. The source was sharded on _id, while DocumentDB queries for this workload performed better when collections were kept un-sharded.</p><p>So the team made the less obvious choice: keep the target collections un-sharded and distribute collections across a smaller number of nodes by storage volume. Linked collections were kept together on the same node to avoid unnecessary cross-node behavior.</p><p>The final target was a 3-node, 16 TB cluster.</p><p>That is the part of the story I like most, because it runs against a common migration instinct. The goal is not to reproduce the source. The goal is to design the target for the workload you actually want to run.</p><h3>Four jobs, not one giant job</h3><p>Tooling has limits too.</p><p>A single job trying to handle thousands of collections proved too large. Resume token tracking was not reliable for some collections. Large 16 MB documents created change stream limitations. These were not theoretical risks; they surfaced during UAT.</p><p>That is why UAT mattered.</p><p>The team used UAT not just to validate the migration path, but to train the customer team, identify tool gaps, fix issues, and refine the production runbook before production data was at risk.</p><p>The final production approach split the work into <strong>four balanced migration jobs</strong>:</p><ol><li>Two jobs carried the largest and highest-throughput collections.</li><li>Two jobs carried the remaining collections, distributed to balance offline and online load.</li></ol><p>That split was simple enough to operate but structured enough to avoid concentrating too much load in one place.</p><p>The jobs ran at full speed, but not blindly. Source and target utilization were monitored manually. When pressure rose, the team throttled. When the system had room, the jobs continued flat out.</p><p>This was not a “set it and forget it” migration. It was a controlled burn.</p><h3>What actually made the cutover work</h3><p>Looking back, the successful pattern was not one big trick. It was a sequence of disciplined choices.</p><p><strong>Assess first.</strong> Every major decision came from real assessment data, not guesswork.</p><p><strong>Prove it in UAT.</strong> The team used UAT to validate tooling, discover failure modes, and skill up the operators before production.</p><p><strong>Defer what slows ingestion.</strong> HA, cross-region replicas, and non-unique index builds were postponed until after the bulk load.</p><p><strong>Do not blindly mirror the source.</strong> The target stayed un-sharded because that fit the workload better than copying the source topology.</p><p><strong>Split the work intentionally.</strong> Four balanced jobs gave the team enough parallelism without creating operational chaos.</p><p><strong>Copy only what matters.</strong> Junk collections were skipped, and large collections were filtered to relevant documents.</p><p><strong>Watch the system continuously.</strong> The jobs ran aggressively, but utilization was monitored and throttled when needed.</p><p>The result was a large-scale migration completed inside a tight cutover window.</p><p>That sounds like a scale story.</p><p>But the real story is simpler: plan with evidence, test where mistakes are cheap, move only what matters, and do the expensive things in the right order.</p><p>That is how large migrations become boring.</p><p>And boring, in database migrations, is a compliment.</p><p><em>Azure DocumentDB is a MongoDB-compatible database service, built on the </em><a href="https://github.com/documentdb/documentdb"><em>MIT licensed open-source DocumentDB project</em></a><em>.</em></p><p><em>For more Azure DocumentDB stories, </em><a href="https://www.linkedin.com/in/abinavrameesh/"><em>follow Abinav Rameesh on LinkedIn</em></a><em>.</em></p><p><em>And if you’re exploring Azure DocumentDB for your team, follow the </em><a href="https://www.linkedin.com/company/azuredocumentdb"><em>Azure DocumentDB page</em></a><em> for product updates and community content.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=789376a9c98e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>