<?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 Siddhant Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Siddhant Srivastava on Medium]]></description>
        <link>https://medium.com/@siddhantsrivastava_27?source=rss-48884f7481ea------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ur8z50aqHAOnU12fg2BI8w.jpeg</url>
            <title>Stories by Siddhant Srivastava on Medium</title>
            <link>https://medium.com/@siddhantsrivastava_27?source=rss-48884f7481ea------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:00:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siddhantsrivastava_27/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[How to Set Up Application Performance Monitoring Using OpenTelemetry]]></title>
            <link>https://medium.com/@siddhantsrivastava_27/how-to-set-up-application-performance-monitoring-using-opentelemetry-1ba5d50779db?source=rss-48884f7481ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ba5d50779db</guid>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[grafana-loki]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[grafana-tempo]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Siddhant Srivastava]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 19:08:14 GMT</pubDate>
            <atom:updated>2026-07-26T19:08:14.685Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was load-testing one of our backend applications using a Lua script when I noticed something concerning: our <strong>P95 latency was much higher than expected</strong>.</p><p>Finding that number wasn’t the hardest part but I couldn’t understand for what reason is that so high?</p><p>Was MongoDB taking too long? Were S3 calls slow? Was an external API holding up requests? Or was the problem somewhere inside our own application?</p><p>At that point, infrastructure metrics like CPU utilisation and memory usage weren’t enough. They could tell me that something was wrong, but not necessarily <strong>where the application was spending its time</strong>.</p><p>I needed visibility inside individual requests.</p><p>That’s when I started exploring <strong>Application Performance Monitoring (APM)</strong> and eventually landed on <strong>OpenTelemetry</strong>.</p><p>Since we already had Grafana running for infrastructure monitoring, the Grafana observability stack fit naturally into our setup.</p><p>The idea is fairly simple:</p><pre>Metrics → What is going wrong?<br>Traces  → Where is it going wrong?<br>Logs    → Why did it go wrong?</pre><p>The architecture looks roughly like this:</p><pre>                        Application<br>                              |<br>                     OpenTelemetry SDK<br>                              |<br>                             OTLP<br>                              |<br>                              v<br>                  OpenTelemetry Collector<br>                   /          |          \<br>                  /           |           \<br>                 v            v            v<br>          Span Metrics      Traces        Logs<br>                 |            |            |<br>                 v            v            v<br>          Metrics Backend    Tempo         Loki<br>        (VictoriaMetrics)      |            |<br>                  \            |           /<br>                   \           |          /<br>                            Grafana</pre><p>Here’s how you can build a similar setup.</p><h3>1. Instrument the Application with OpenTelemetry</h3><p>The first step is getting telemetry out of the application.</p><p>OpenTelemetry provides instrumentation libraries for popular frameworks, databases and HTTP clients, so you don’t necessarily have to manually create a span around every operation.</p><p>For a FastAPI application, install the OpenTelemetry SDK, OTLP exporter and the instrumentation packages you need.</p><pre>pip install \<br>    opentelemetry-api \<br>    opentelemetry-sdk \<br>    opentelemetry-exporter-otlp-proto-grpc \<br>    opentelemetry-instrumentation-fastapi \<br>    opentelemetry-instrumentation-httpx \<br>    opentelemetry-instrumentation-requests \<br>    opentelemetry-instrumentation-pymongo \<br>    opentelemetry-instrumentation-botocore \<br>    opentelemetry-instrumentation-logging</pre><p>In my application, the setup looks roughly like this:</p><pre>import logging<br>from fastapi import FastAPI<br>from opentelemetry import _logs, trace<br>from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter<br>from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter<br>from opentelemetry.instrumentation.botocore import BotocoreInstrumentor<br>from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor<br>from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor<br>from opentelemetry.instrumentation.logging import LoggingInstrumentor<br>from opentelemetry.instrumentation.pymongo import PymongoInstrumentor<br>from opentelemetry.instrumentation.requests import RequestsInstrumentor<br>from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler<br>from opentelemetry.sdk._logs.export import BatchLogRecordProcessor<br>from opentelemetry.sdk.resources import Resource<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor<br><br>def setup_opentelemetry(app: FastAPI, service_name: str, endpoint: str):<br>    resource = Resource.create({<br>        &quot;service.name&quot;: service_name,<br>    })<br>    # Tracing<br>    tracer_provider = TracerProvider(resource=resource)<br>    tracer_provider.add_span_processor(<br>        BatchSpanProcessor(<br>            OTLPSpanExporter(<br>                endpoint=endpoint,<br>                insecure=True,<br>            )<br>        )<br>    )<br>    trace.set_tracer_provider(tracer_provider)<br>    # Logging<br>    logger_provider = LoggerProvider(resource=resource)<br>    logger_provider.add_log_record_processor(<br>        BatchLogRecordProcessor(<br>            OTLPLogExporter(<br>                endpoint=endpoint,<br>                insecure=True,<br>            )<br>        )<br>    )<br>    _logs.set_logger_provider(logger_provider)<br>    logging.getLogger().addHandler(<br>        LoggingHandler(<br>            level=logging.NOTSET,<br>            logger_provider=logger_provider,<br>        )<br>    )<br>    LoggingInstrumentor().instrument(set_logging_format=False)<br>    # Automatic instrumentation<br>    FastAPIInstrumentor.instrument_app(<br>        app,<br>        tracer_provider=tracer_provider,<br>    )<br>    HTTPXClientInstrumentor().instrument(<br>        tracer_provider=tracer_provider,<br>    )<br>    RequestsInstrumentor().instrument(<br>        tracer_provider=tracer_provider,<br>    )<br>    BotocoreInstrumentor().instrument(<br>        tracer_provider=tracer_provider,<br>    )<br>    PymongoInstrumentor().instrument(<br>        tracer_provider=tracer_provider,<br>    )</pre><p>You don’t need all these instrumentors. Pick the ones your application actually uses.</p><p>For example, in my case:</p><pre>FastAPI       → incoming HTTP requests<br>HTTPX         → outgoing HTTP requests<br>Requests      → outgoing HTTP requests<br>PyMongo       → MongoDB operations<br>Botocore      → AWS calls such as S3<br>AIOKafka      → Kafka operations</pre><p>This is where things start getting interesting.</p><p>Instead of only knowing:</p><pre>POST /generate-nit → 8.2 seconds</pre><p>you can eventually see something closer to:</p><pre>POST /generate-nit                 8.2s<br>│<br>├── authentication                 20ms<br>├── MongoDB query                  84ms<br>├── OpenSearch request            340ms<br>├── document extraction            1.2s<br>├── external API request           5.9s<br>└── MongoDB save                  110ms</pre><p>Now we can actually answer the question we started with: <strong>where is the request spending its time?</strong></p><h3>2. Add the OpenTelemetry Collector</h3><p>You can send telemetry directly from your application to different backends, but putting the <strong>OpenTelemetry Collector</strong> in between gives you a much cleaner architecture.</p><p>Your applications only need to know one thing:</p><pre>Send telemetry here → otel-collector:4317</pre><p>The Collector handles where that telemetry needs to go.</p><p>This becomes especially useful once you have multiple services:</p><pre>Service A ──┐<br>Service B ──┼──&gt; OpenTelemetry Collector ──&gt; Observability Backends<br>Service C ──┘</pre><p>A simplified Collector configuration looks like this:</p><pre>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>        endpoint: 0.0.0.0:4317<br>      http:<br>        endpoint: 0.0.0.0:4318<br>processors:<br>  memory_limiter:<br>    check_interval: 5s<br>    limit_mib: 400<br>  batch:<br>connectors:<br>  spanmetrics:<br>    dimensions:<br>      - name: http.method<br>      - name: http.status_code<br>      - name: http.route<br>exporters:<br>  otlp/tempo:<br>    endpoint: tempo:4317<br>    tls:<br>      insecure: true<br>  prometheusremotewrite/metrics:<br>    endpoint: http://victoriametrics:8428/api/v1/write<br>  otlphttp/loki:<br>    endpoint: http://loki:3100/otlp<br>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [otlp/tempo, spanmetrics]<br>    metrics:<br>      receivers: [otlp, spanmetrics]<br>      processors: [memory_limiter, batch]<br>      exporters: [prometheusremotewrite/metrics]<br>    logs:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [otlphttp/loki]</pre><p>There are two processors here worth mentioning.</p><p>batch groups telemetry together before exporting it instead of sending every event individually.</p><p>memory_limiter prevents the Collector from consuming too much memory when the amount of telemetry suddenly increases — something that becomes particularly useful during load testing.</p><p>With this configuration, our Collector becomes the central routing layer:</p><pre>                     OTel Collector<br>                    /      |       \<br>                   /       |        \<br>                  v        v         v<br>              Metrics    Traces     Logs<br>                 |         |         |<br>                 v         v         v<br>         VictoriaMetrics  Tempo     Loki</pre><h3>3. Store Distributed Traces with Grafana Tempo</h3><p>The Collector receives our traces, but we still need somewhere to store and query them.</p><p>That’s where <strong>Grafana Tempo</strong> comes in.</p><p>A minimal Tempo configuration can look like:</p><pre>server:<br>  http_listen_port: 3200<br>distributor:<br>  receivers:<br>    otlp:<br>      protocols:<br>        grpc:<br>        http:<br>storage:<br>  trace:<br>    backend: local<br>    local:<br>      path: /var/tempo/traces</pre><p>For production, you’d normally use object storage such as S3 instead of local storage.</p><p>Once Tempo is connected as a Grafana data source, Grafana’s Explore view lets you inspect individual traces and their spans.</p><p>This was the missing piece for my original problem.</p><p>Instead of guessing why P95 latency was high, I could inspect slow requests and see where they actually spent their time.</p><h3>4. Generate APM Metrics from Traces</h3><p>Traces are great when debugging individual requests.</p><p>But we also want aggregate information such as:</p><ul><li>request rate</li><li>error rate</li><li>average latency</li><li>P95/P99 latency</li><li>latency by endpoint</li><li>latency by service</li></ul><p>One useful approach is generating these metrics from the traces we’re already collecting.</p><p>The OpenTelemetry Collector provides the <strong>Span Metrics Connector</strong> for exactly this purpose.</p><p>Conceptually:</p><pre>                        Traces<br>                           |<br>                           v<br>Application ──────&gt; OTel Collector ──────&gt; Tempo<br>                           |<br>                      spanmetrics<br>                           |<br>                           v<br>                      APM Metrics<br>                           |<br>                           v<br>                    Metrics Backend</pre><p>Configure the connector:</p><pre>connectors:<br>  spanmetrics:<br>    dimensions:<br>      - name: http.method<br>      - name: http.status_code<br>      - name: http.route</pre><p>Then connect it to both pipelines:</p><pre>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [otlp/tempo, spanmetrics]<br>    metrics:<br>      receivers: [otlp, spanmetrics]<br>      processors: [memory_limiter, batch]<br>      exporters: [prometheusremotewrite/metrics]</pre><p>Now traces passing through the Collector automatically generate application-level metrics.</p><p>Those metrics can be stored in any suitable Prometheus-compatible backend.</p><p>I’m using <strong>VictoriaMetrics</strong>, so the Collector sends them using Prometheus Remote Write:</p><pre>exporters:<br>  prometheusremotewrite/metrics:<br>    endpoint: http://victoriametrics:8428/api/v1/write</pre><p>If you’re already using Prometheus or another Prometheus-compatible metrics backend, you can use that instead.</p><p>The important part isn’t the particular database.</p><p>The important part is that the same telemetry giving us individual traces can now also produce the aggregate metrics used by our APM dashboard.</p><h3>5. Add Loki for Centralised Logging</h3><p>Loki isn’t strictly required for APM, but I highly recommend adding it.</p><p>Since we’re already sending telemetry through OpenTelemetry, logs can travel through the same Collector:</p><pre>Application<br>     |<br>OpenTelemetry<br>     |<br>     v<br>OTel Collector<br>     |<br>     v<br>    Loki</pre><p>The Collector configuration is straightforward:</p><pre>exporters:<br>  otlphttp/loki:<br>    endpoint: http://loki:3100/otlp<br>service:<br>  pipelines:<br>    logs:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [otlphttp/loki]</pre><p>Without centralised logging, you might find a problematic trace and then have to search container logs manually.</p><p>With Loki, those logs become searchable directly from Grafana.</p><p>Our debugging flow now becomes:</p><pre>High P95 latency<br>       ↓<br>Grafana dashboard<br>       ↓<br>Find problematic service/endpoint<br>       ↓<br>Open trace in Tempo<br>       ↓<br>Find slow span<br>       ↓<br>Inspect related logs in Loki</pre><p>Even better, OpenTelemetry can attach trace and span context to logs.</p><p>For example:</p><pre>trace_id = 4bf92f3577b34da6a3ce929d0e0e4736<br>span_id  = 00f067aa0ba902b7</pre><p>That makes it possible to correlate logs with the request that produced them.</p><p>This is where centralised logging becomes much more useful than simply having a place where all your logs are stored.</p><h3>6. Connect Everything to Grafana</h3><p>At this point we have three main pieces:</p><pre>VictoriaMetrics → Application/APM metrics<br>Tempo           → Distributed traces<br>Loki            → Application logs</pre><p>Add these as data sources in Grafana:</p><pre>Connections<br>    ↓<br>Data Sources<br>    ↓<br>Add data source</pre><p>For VictoriaMetrics, you can configure it using Grafana’s Prometheus-compatible data source.</p><p>Then add Tempo and Loki as their respective data sources.</p><p>Once everything is connected, Grafana becomes the place where we actually investigate the application.</p><h3>7. Import an OpenTelemetry APM Dashboard</h3><p>You don’t necessarily have to build your first dashboard from scratch.</p><p>One dashboard I found useful is Grafana’s <strong>OpenTelemetry APM dashboard</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oc4ANa7EHJn9qN6N" /></figure><p>Open Grafana:</p><p><strong>Dashboards → New → Import</strong></p><p>Then import dashboard:</p><p><strong>19419</strong></p><p>The dashboard is available here:</p><p><a href="https://grafana.com/grafana/dashboards/19419-opentelemetry-apm/">https://grafana.com/grafana/dashboards/19419-opentelemetry-apm/</a></p><p>It works with metrics generated from OpenTelemetry traces using the Span Metrics Connector and gives you a good starting point for application-level monitoring.</p><p>You get visibility into things such as request rate, errors and latency without having to build every panel manually.</p><p>From there, you can customise the dashboard based on your application’s requirements.</p><h3>Putting Everything Together</h3><p>Our final architecture now looks like this:</p><pre>                        Backend Services<br>                               |<br>                        OpenTelemetry SDK<br>                               |<br>                              OTLP<br>                               |<br>                               v<br>                    OpenTelemetry Collector<br>                      /        |        \<br>                     /         |         \<br>                    v          v          v<br>             Span Metrics    Traces      Logs<br>                    |          |          |<br>                    v          v          v<br>            VictoriaMetrics   Tempo      Loki<br>                     \         |         /<br>                      \        |        /<br>                           Grafana<br>                              |<br>                 +------------+------------+<br>                 |                         |<br>            APM Dashboard               Explore<br>                 |                         |<br>          P95 latency spike        Individual trace<br>                                           |<br>                                       Related logs</pre><p>And that’s the part I like most about this setup.</p><p>I started with a very simple problem:</p><blockquote><strong><em>Why is my P95 latency so high?</em></strong></blockquote><p>Before setting up APM, I could see that the application was slow, but I couldn’t confidently tell <em>why</em>.</p><p>After setting up OpenTelemetry, I now have three different levels of visibility:</p><pre><strong>Metrics</strong><br>   ↓<br>Which service or endpoint is having problems?<br><br><strong>Traces</strong><br>   ↓<br>Which operation inside that request is slow?<br><br><strong>Logs</strong><br>   ↓<br>What actually happened during that operation?</pre><p>So instead of stopping at:</p><p><strong>“Our API is slow.”</strong></p><p>we can move to:</p><p><strong>“This endpoint has high P95 latency.”</strong></p><p>then:</p><p><strong>“These particular requests are slow.”</strong></p><p>and finally:</p><p><strong>“This MongoDB/S3/external API call is where we’re spending most of our time.”</strong></p><p>That’s the real value of Application Performance Monitoring.</p><p>It doesn’t magically make your application faster.</p><p>It gives you the visibility you need to figure out <strong>what actually needs fixing</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ba5d50779db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Production-Ready MongoDB Backup System on AWS]]></title>
            <link>https://medium.com/@siddhantsrivastava_27/how-i-built-a-production-ready-mongodb-backup-system-on-aws-e98840ff5032?source=rss-48884f7481ea------2</link>
            <guid isPermaLink="false">https://medium.com/p/e98840ff5032</guid>
            <category><![CDATA[incremental-backup]]></category>
            <category><![CDATA[mongodump]]></category>
            <category><![CDATA[backup-restore]]></category>
            <category><![CDATA[mongodb-backup]]></category>
            <category><![CDATA[full-backup]]></category>
            <dc:creator><![CDATA[Siddhant Srivastava]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 14:49:46 GMT</pubDate>
            <atom:updated>2026-04-05T16:53:23.977Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, as our system stabilized, my team realized we lacked something critical, a reliable way to recover our data. Our MongoDB setup was live, replicated, and running on AWS, which gave us confidence in its availability. But availability is not the same as recoverability. None of this protected us from logical failures like accidental deletions, faulty updates, or bad deployments.</p><p>I was tasked with designing a backup strategy for our system, and that’s where the real learning began. In this blog, I’ll walk through the questions I explored, the methodology I implemented, and how to build a production-ready MongoDB backup system on AWS.</p><h3>Why take backups when data is already on an EC2 instance?</h3><p>At first glance, running MongoDB on an AWS EC2 instance feels safe enough. After all, the data is already stored on persistent volumes like EBS, and AWS provides high availability for infrastructure. However, this creates a false sense of security. EC2 and EBS ensure that your machine and disk are available but they do not guarantee that your data is safe from logical errors or human mistakes.</p><p>In real-world systems, data loss rarely happens because of hardware failure alone. It often happens due to application-level bugs, accidental deletions, incorrect migrations, or even simple developer errors like dropping a collection or overwriting critical fields. These changes are instantly persisted to your database and replicated if you’re using a replica set. Without backups, there is no way to go back to a previous correct state.</p><p>This is the key distinction: infrastructure ensures availability, but backups ensure recoverability. A system without backups is not resilient, it is fragile. No matter how reliable your cloud provider is, you still need a mechanism to recover your data to a known good state.</p><h3>Backing up a self-managed MongoDB on AWS (My Approach)</h3><p>When using a self-managed MongoDB instance on AWS instead of a managed service like MongoDB Atlas, you are responsible for designing and maintaining your own backup strategy. In my setup, MongoDB runs on EC2 instances, and I implemented a combination of full and incremental backups using <strong>mongodump</strong> along with MongoDB’s <a href="https://www.mongodb.com/docs/manual/core/replica-set-oplog/"><strong>oplog</strong></a>.</p><p>The idea is straightforward but powerful. A full backup is taken periodically (once a day), which captures the entire state of the database. Along with this, I store the latest oplog timestamp. Then, at regular intervals (for example, every hour), I take incremental backups by dumping only the operations from the oplog that occurred after the last recorded timestamp. This allows me to capture all changes without repeatedly backing up the entire dataset.</p><p>To automate the entire process, I used cron jobs for scheduling and AWS S3 as the storage backend. Backups are generated at regular intervals, uploaded to S3, and removed locally only after successful verification to prevent any risk of data loss. This approach maintains a balance between simplicity and reliability while supporting point-in-time recovery. The entire workflow is defined through scripts integrated into my Terraform configuration, ensuring consistency, reproducibility, and ease of management across environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VozixG0UWkBqaLaoMxOodg.png" /><figcaption>Figure 1: Full + incremental backup flow to S3</figcaption></figure><h3>What is the difference between full backup and incremental backup?</h3><p>A full backup is a complete snapshot of your database at a specific point in time. It includes all collections, documents, and metadata. While it is simple and reliable, it can be expensive in terms of time, storage, and compute resources, especially for large databases.</p><p>Example script for full backup using mongodump:</p><pre>  mongodump $AUTH_ARGS \<br>    --oplog \<br>    --gzip \<br>    --archive=&quot;$FULL_FILE&quot;</pre><p>An incremental backup, on the other hand, captures only the changes that occurred after the last backup. In MongoDB, this is achieved using the oplog, which records all write operations in the database. By querying the oplog with a timestamp filter, you can extract only the new operations and store them separately.</p><p>Example script for incremental backup using mongodump(oplog-based):</p><pre>  mongodump $AUTH_ARGS \<br>    --db local \<br>    --collection oplog.rs \<br>    --queryFile &quot;$QUERY_FILE&quot; \<br>    --out &quot;$INCR_DUMP_DIR&quot;</pre><p>The real power comes from combining both approaches. A full backup provides a baseline, and incremental backups allow you to reconstruct the database state at any point after that baseline. This combination enables Point-in-Time Recovery (PITR), which is critical for production systems where even a few minutes of data loss can be unacceptable.</p><h3>How to take backups in different scenarios?</h3><p>The strategy for taking backups depends heavily on how your MongoDB is deployed.</p><p>In a single-node setup, there is only one instance acting as the primary. In this case, backups must run on the same node. While this is simple to implement, it comes with trade-offs. Backup operations can consume CPU and disk I/O, potentially affecting application performance. There is also no redundancy i.e. if the node fails during backup, you risk losing both live data and backup data. If you’re on a single node, schedule backups during off-peak hours and monitor backup duration to minimize impact.</p><p>In a two-node setup (primary and secondary), a much better approach is to run backups on the secondary node. Since the secondary is continuously replicating data from the primary, it has an up-to-date copy of the database. Running backups on the secondary avoids putting additional load on the primary, ensuring that write operations remain unaffected.</p><p>In larger replica sets with one primary and multiple secondary nodes, the best practice is to dedicate one secondary node specifically for backups because if multiple nodes independently take backups, it can lead to redundant data, increased storage costs, and unnecessary strain on the cluster. Additionally, backups taken from different nodes at slightly different replication states may introduce inconsistencies when trying to restore a precise point in time. This node can handle all backup-related operations without interfering with application traffic or replication performance. A simple but important rule in such setups is to always detect if a node is primary and skip backups on it. This ensures that your primary remains focused on serving application requests.</p><h3>Where to safely store these backups and the folder structure I prefer</h3><p>Storing backups on the same machine as your database defeats the purpose of having backups. If the instance fails or gets compromised, both your data and backups are lost. This is why it is essential to store backups in a separate, durable storage system. AWS S3 is an excellent choice for this due to its high durability, scalability, and cost-effectiveness.</p><p>A well-organized folder structure is just as important as the backup process itself. In my setup, backups are stored in a date-based hierarchy, where each date acts as an isolated snapshot of that day’s data. Within each date, there is a dedicated location for the full backup along with an incremental directory that contains all incremental backups taken throughout the day. To ensure correct ordering, each incremental backup is named using its creation timestamp (converted to epoch time), making it easy to replay changes in the exact sequence they occurred.</p><p>This structure makes it easy to locate backups for a specific date and simplifies the restore process. Additionally, using S3 lifecycle policies, older backups can be automatically deleted after a certain period, ensuring efficient storage management without manual intervention.</p><h3>How to easily restore these backups?</h3><p>Taking backups is only half the job, restoring them correctly is what truly matters. The restore process typically begins with restoring the full backup, which brings the database back to the baseline state. This is done using <strong>mongorestore.</strong></p><p>Example full backup restoration script:</p><pre>mongorestore --host &lt;host&gt; --port &lt;port&gt; \<br>  --username &lt;user&gt; --password &lt;pass&gt; \<br>  --authenticationDatabase admin \<br>  --gzip --archive=&quot;full_backup.gz&quot; \<br>  --drop --oplogReplay</pre><p>Once the full backup is restored, incremental backups must be applied in sequence. Since each incremental backup contains operations from the oplog, they must be replayed in the exact order they were captured. This step reconstructs all changes that occurred after the full backup, effectively bringing the database to the desired point in time.</p><p>Example incremental backup restoration script:</p><pre>for INCR_DIR in $(ls -d /restore/path/&lt;DATE&gt;/incre_backup-*/ | sort); do<br>  EMPTY_DIR=$(mktemp -d)<br>  mongorestore --host &lt;host&gt; --port &lt;port&gt; \<br>    --username &lt;user&gt; --password &lt;pass&gt; \<br>    --authenticationDatabase admin \<br>    --oplogReplay \<br>    --oplogFile=&quot;$INCR_DIR/local/oplog.rs.bson&quot; \<br>    --dir=&quot;$EMPTY_DIR&quot;<br>  rm -rf &quot;$EMPTY_DIR&quot;<br>done</pre><p>One important aspect to understand is that MongoDB does not automatically merge incremental backups, you must explicitly apply them. This means your backup strategy must ensure proper ordering and consistency of incremental files.</p><p>The biggest mistake teams make is assuming that backups guarantee recovery. In reality, a backup is only useful if it has been tested through a successful restore. Regularly testing restore procedures is essential to ensure that your backup system actually works when needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e98840ff5032" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>