Full Blog TOC

Full Blog Table Of Content with Keywords Available HERE

Monday, November 23, 2026

How to Migrate a Production Service with AI Coding Agents



A customer clicks Export. The new service returns the same HTTP 202 as the old one. The test passes. But the worker never receives a job, and the customer keeps waiting for a file that will never arrive.

This is the hard part of a production migration. An AI coding agent can move a lot of code quickly. It needs a way to see what the old service does, including the work that happens after the response. I start with one workflow, give the agent a reusable migration skill, and write down how we will know when that workflow is ready.

Start with One Workflow

“Rewrite the export service” makes for a poor assignment. “A user requests an export and can download the finished file” gives the agent a path to trace and the reviewer an outcome to verify.

Ask the agent to follow the workflow from the entry point to its last observable effect. For an export, the API creates a job, a worker writes a file, and the user checks the job status. Find out what happens if the queue delivers the same message twice or the worker fails after writing the file. Map the dependencies that matter to that behavior.

Then decide what to move. The new service might own the API while the existing worker keeps running behind the same queue. Reusing that boundary can turn a service rewrite into a much smaller change. Record who owns each write during the transition, especially when both versions are live.

Put the Repeated Work in a Skill

A migration skill is a set of instructions the coding agent loads whenever it moves a workflow. Put it in a versioned SKILL.md where the team can review it. Give it a description that says when it applies, and link to the repository's coding rules, test setup, and migration plan. Keep decisions about each workflow in the plan so the skill stays usable on the next one.

Here is a migration skill you can adapt.

  1. Build the task from current evidence. Read the existing plan, then trace the active entry points and their callers in both implementations. Check each supported client or build that can reach the workflow. Record the source and destination paths, what already works, and the behavior still missing. Treat a disagreement between the plan and the running code as something to investigate.
  2. Assign each operation to an owner. Identify who handles the request, who writes state, who publishes or consumes events, and who owns startup and configuration. Use the target system's existing clients, queues, and worker setup where they preserve the required behavior. Record any new dependency and the reason it is needed.
  3. Define the contract before editing. List the public responses, state changes, background work, and failure behavior that callers rely on. Include cases such as duplicate delivery or partial failure where they affect the workflow. Label intentional behavior changes in the task and get a decision on ambiguous ones before implementing them.
  4. Verify through the normal entry point. Run the same acceptance cases against the old and new service where possible. Start the real handlers and workers through the usual registration and initialization paths. Use controlled infrastructure dependencies to trigger failures, and keep the test assertions on observable outcomes. If a database stub cannot model locking, record that limit and verify the concurrency behavior against the real database before relying on it.
  5. Finish the workflow through its callers. Check that clients, routes, event readers, configuration, and fixtures agree with the migrated contract. Before removing an old path, search for remaining callers and map its acceptance checks to their replacements. Keep the migration status open while required dependencies or checks are pending.
  6. Hand off evidence. Report what changed, which checks ran, which were skipped or blocked, and what remains before cutover. An independent reviewer should be able to follow the legacy path and reproduce the important checks from that handoff.

For the export example, the task can be a few lines. The request endpoint already exists. The missing behavior is handing the job to the existing worker and showing the finished file to the caller. The queue contract is a dependency. The acceptance evidence is an export completed through the public API, including a test that redelivers the job. The skill tells the agent how to get that evidence and what to report if it cannot.

Keep repository conventions in their own skill. The migration skill should work whether the target is written in Go, Python, or the same language as the original service. For an example of packaging coding conventions for an agent, see GO Coding Guideline as Agent Skill.

Run the Tests Against the Old Service First

Before asking the agent to implement anything, run the acceptance cases against the legacy service. Use equivalent starting data for each run. Check the response and the downstream effects that callers rely on.

For the export example, a useful test requests an export, waits for completion, and verifies that the file contains the expected rows. A second test redelivers the worker message and checks that there is still one completed export. A third makes storage temporarily unavailable and checks that the user eventually sees the expected result or a clear failure.

Compare fields such as timestamps and generated IDs by their meaning. A new job ID can be valid as long as it identifies the same job throughout the workflow. If the legacy system behaves in a surprising way, record whether you will preserve it or change it deliberately. That decision belongs in the task so a reviewer can tell an intentional change from a regression.

Review the Evidence and Keep the Next Task Small

Give the implementation agent a workflow, the agreed behavior, and the command that runs its tests. Give the reviewer the same task and the legacy entry point. Ask the reviewer which important behavior could still be broken with every test passing. That question often produces a better test than another pass over the diff.

Keep the migration plan in the repository. One row per workflow is usually enough. Include the owner, dependencies, current status, and a link to the checks. Use specific states such as mapped, parity verified, and live. A workflow can pass every acceptance test and still be waiting for a queue or a deployment change.

For more on defining a clear result when delegating to an agent, see How I Get at Least 10x More Work Done with an AI Coding Agent.

Move Traffic When You Can Move It Back

Start with a small cohort and pick the signals that will decide whether to expand it. For the export workflow, watch time to completion, failed jobs, and queue age alongside HTTP errors. A healthy API can still have a stalled worker.

Before raising traffic, check what happens when you route new requests back to the old service. Jobs already queued and records already written still exist. If the old worker cannot read the new job format, agree on how to drain those jobs or keep both versions compatible before switching traffic.

For the deployment mechanics, see Zero-Downtime Kubernetes Deployments.

Final Note

Start with one workflow that has a clear outcome and a dependency you can observe. Write down the behavior, run the checks against the old service, and turn the steps you expect to repeat into a skill. When a review finds a mistake that could recur, add the general rule to the skill. For example, if a workflow was missed because the agent inspected only one client, add a check for every active client. When you hand the next workflow to another agent, it should be able to start from the plan, run the checks, and show you what still needs a decision.

Wednesday, November 18, 2026

Zero-Downtime Kubernetes Deployments: Readiness, Rolling Updates, and Graceful Shutdown



In this post we will review how to deploy a new application version on Kubernetes without interrupting requests. We will combine readiness probes, rolling updates, and graceful shutdown, then check what happens while the old and new versions run together.

Assume we have an HTTP API behind a Kubernetes Service and an ingress. A request normally takes less than a second, but some requests take 20 seconds. We want to replace the application image while clients continue using the API.

Setting the deployment strategy to RollingUpdate is a good start. However it does not tell Kubernetes when the application has finished initialization, or tell the application how to finish an accepted request before exiting.

These decisions need to agree.

The Deployment Problem

An application can fail during deployment in several ways.

The new pod starts listening before loading its configuration. Kubernetes sends it a request, and the request fails because initialization is incomplete.

The old pod receives a termination signal and closes its connections immediately. A request that was almost complete now fails at the client.

The application waits for requests, but closes its database pool first. The connection remains open, but the handler can no longer finish its work.

In all these cases the Deployment can eventually report success. That tells us the desired pods became available; it does not prove that clients experienced no errors along the way.

Define When the Application Is Ready

Use separate endpoints for separate questions:

  • /live: Is the process healthy enough to keep running?
  • /ready: Can this instance accept application traffic now?

The readiness endpoint should return HTTP 503 during initialization, HTTP 200 when the instance can serve requests, and HTTP 503 again when draining begins.

Opening the HTTP port is not sufficient. Depending on the service, initialization can include loading configuration, preparing shared storage access, or establishing the subscriptions needed to process requests.

Keep the readiness check cheap. It can inspect initialization and draining state plus carefully chosen dependency checks. An expensive database query on every probe creates another source of load.

Liveness should normally remain independent of a temporary database or messaging outage. Restarting every application pod during a shared dependency failure can make recovery harder.

I introduced these probe concepts in an earlier NodeJS example: Create NodeJS Service with Kubernetes Liveness and Readiness Probes

Configure the Rolling Update

The following Deployment illustrates the relevant settings. Replace the image with your own application, implementing /live and /ready on port 8080. The container must include /bin/sleep for the preStop hook shown here.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-api
spec:
  replicas: 2
  minReadySeconds: 10
  progressDeadlineSeconds: 600
  selector:
    matchLabels:
      app: example-api
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
  template:
    metadata:
      labels:
        app: example-api
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: api
          image: registry.example.com/example-api:1.0.0
          ports:
            - name: http
              containerPort: 8080
          resources:
            requests:
              cpu: "250m"
              memory: "256Mi"
            limits:
              memory: "512Mi"
          startupProbe:
            httpGet:
              path: /live
              port: http
            periodSeconds: 5
            timeoutSeconds: 2
            failureThreshold: 60
          readinessProbe:
            httpGet:
              path: /ready
              port: http
            periodSeconds: 2
            timeoutSeconds: 1
            failureThreshold: 1
          livenessProbe:
            httpGet:
              path: /live
              port: http
            periodSeconds: 10
            timeoutSeconds: 2
            failureThreshold: 3
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sleep", "10"]

maxSurge: 1 permits one extra pod during the rollout. maxUnavailable: 0 prevents the Deployment controller from intentionally reducing available pods below the desired count during replacement. It does not prevent a pod from crashing or a node from failing.

minReadySeconds: 10 requires a new pod to remain ready for ten seconds before it counts as available. This helps avoid replacing an old pod immediately after a brief successful readiness check.

The startup probe gives the local health endpoint roughly five minutes to become healthy before repeated startup failures cause a restart. Readiness and liveness probes wait until startup succeeds. Here /live only establishes local health; /ready still gates application initialization afterward.

progressDeadlineSeconds makes a stalled rollout visible through the Deployment status. It does not automatically roll back a failed release.

The Service Must Select Ready Pods

The corresponding Service is simple:

apiVersion: v1
kind: Service
metadata:
  name: example-api
spec:
  selector:
    app: example-api
  ports:
    - port: 80
      targetPort: http

Keep the default behavior of publishing ready endpoints. Enabling publishNotReadyAddresses for this client-facing Service would undermine the readiness boundary.

Readiness controls normal Service routing, but routing changes take time to reach all components. Existing connections can also outlive the endpoint update. This is why shutdown needs more than returning HTTP 503 from /ready.

Understand the Termination Timeline

During normal pod deletion, Kubernetes begins updating endpoint information and the kubelet starts container termination. These activities are asynchronous; they are not one perfectly ordered event.

The preStop hook runs before the application receives SIGTERM. In this example it sleeps for ten seconds while the old application continues serving. This gives Service routing and ingress endpoint changes time to propagate before the listener starts shutting down.

The application receives SIGTERM after the hook completes. It should then mark itself draining, stop admitting new work, and wait for work it already accepted.

The shutdown sequence is:

  1. Pod deletion begins; routing components start removing the endpoint.
  2. The preStop delay runs while the application can still serve late traffic.
  3. SIGTERM starts application draining and graceful HTTP shutdown.
  4. Accepted work finishes while its dependencies remain available.
  5. The application closes dependencies and exits.

Ten seconds is an example, not a universal propagation guarantee. Measure the behavior of your actual ingress, load balancer, and connection pools, then configure the delay accordingly.

The container entrypoint must deliver SIGTERM to the application. If a shell launches the executable, use exec or another arrangement that correctly forwards signals.

Drain Requests Before Closing Dependencies

The HTTP server should stop accepting new connections and allow accepted requests to finish within a configured timeout.

For Go applications, http.Server.Shutdown provides this behavior for ordinary HTTP connections. Keep the process alive until Shutdown returns. ListenAndServe returning does not mean all handlers have completed.

Use a fresh shutdown context with its own timeout. Reusing a context that was canceled by SIGTERM would make the shutdown deadline expire immediately.

If the timeout expires, follow an explicit policy for remaining connections. Calling Shutdown alone does not forcibly close every active connection when its context expires.

Keep the database pool, messaging clients, and other handler dependencies open until the work using them has finished. Closing them first defeats graceful shutdown.

Detached goroutines and message consumers need their own admission and completion tracking. http.Server.Shutdown does not wait for every background operation in the process. WebSockets and other hijacked connections also need explicit shutdown handling.

For jobs that must survive process replacement, persist acceptance and provide recovery rather than relying on a long termination timeout. I covered one approach in: Build a PostgreSQL Job Queue with SKIP LOCKED

Budget the Whole Shutdown

terminationGracePeriodSeconds includes the preStop hook. The countdown does not start after the sleep finishes.

For this example, assume the shutdown phases run sequentially:

  • Endpoint propagation delay: 10 seconds
  • HTTP request drain timeout: 30 seconds
  • Other cleanup and exit margin: 20 seconds
  • Total termination grace: 60 seconds

If background work has another independent 30-second drain phase afterward, this budget must grow or the phases must be coordinated differently. Include every shutdown phase that can delay exit.

After the grace period expires, Kubernetes can forcibly terminate the remaining process. Cleanup code cannot finish after SIGKILL.

Long streams need an explicit contract too. A finite shutdown budget cannot preserve a connection that is expected to remain open forever. Define reconnection and recovery behavior for those clients.

Leave Capacity for the Replacement

A surge pod needs somewhere to run. If the cluster cannot schedule it, maxUnavailable: 0 can leave the rollout waiting while the old pods continue serving.

Reserve enough CPU, memory, pod slots, and network capacity for the temporary overlap. Remember that terminating pods can still consume resources while draining; actual resource usage can exceed the simple desired-replicas-plus-surge calculation.

The remaining serving capacity must also handle real traffic. A pod being Ready is not proof that it can absorb twice its normal load. Bound concurrent work and observe latency under the expected rollout conditions: Go Concurrency Limits: Prevent Goroutine Explosions with Backpressure

One steady replica can use maxSurge: 1 and maxUnavailable: 0 to get temporary overlap during a planned release. That still provides no redundancy if the only serving pod fails before its replacement is ready.

Where a PodDisruptionBudget Helps

For two application replicas, we might also configure:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: example-api
spec:
  minAvailable: 1
  selector:
    matchLabels:
      app: example-api

This can restrict voluntary evictions that use the eviction API, such as a normal node drain.

A PodDisruptionBudget does not control the Deployment's rolling update. maxUnavailable and maxSurge control that replacement behavior. It also cannot prevent involuntary node failures or direct pod deletion.

With one replica, minAvailable: 1 can block a voluntary eviction until another suitable pod is available. It does not create the replacement for you.

Make Old and New Versions Compatible

Rolling updates deliberately run different versions at the same time.

Both versions must understand the shared data and messages used during that overlap. A renamed database column can break old pods even when every readiness probe passes.

Use an expand-and-contract migration: add the new schema in a compatible form, deploy code that can work through the transition, migrate data if needed, and remove the old representation only after older code no longer needs it. Include the rollback window in this decision.

Sessions, download results, and accepted jobs must also remain accessible after a request moves to another pod. Pod-local memory or files cannot provide that by themselves.

An application-only release should avoid unnecessary database or broker restarts. Those components have their own availability and upgrade requirements. For a related database deployment example: Deploy a PostgreSQL Cluster on Kubernetes

Verify Through the Public Endpoint

Run representative traffic through the same ingress or load balancer clients use, then update the Deployment image. A direct request to a pod skips part of the behavior we need to verify.

Include short requests, requests that remain active across termination, and persistent connections. Use enough concurrent traffic to reveal routing gaps and capacity problems. Record errors, timeouts, and latency rather than checking only whether the rollout command succeeds.

Watch the rollout with:

kubectl rollout status deployment/example-api --timeout=10m
kubectl get pods -l app=example-api -w

Check that uninitialized pods receive no application traffic, new pods become available before old ones are removed, and accepted requests complete before dependencies close.

Repeat with a replacement that never becomes ready. The rollout should stall visibly while the existing available pods remain. Also test a request that exceeds the drain timeout, so the forced termination policy is understood before it happens during a release.

If the test client retries automatically, record its first-attempt failures as well. A successful retry can hide an interrupted request, and repeating a write may duplicate its effect without idempotency.

Kubernetes logs can help connect these client results to pod initialization and shutdown events: Collecting Kubernetes Logs using LOKI

Final Note

A reliable rolling deployment needs agreement between the application and Kubernetes.

Readiness keeps new instances out of traffic until they can serve. Rolling update settings preserve available capacity during replacement. Graceful shutdown lets old instances complete accepted work before their dependencies disappear.

Combine these with compatible application versions, enough temporary capacity, and a rollout test through the real client path. That is how we establish whether a deployment actually avoids interrupted requests.

Sunday, November 8, 2026

Limit HTTP Request Body Size in Go: Handle Chunked and Gzip Requests Safely

A stone spillway controls a powerful mountain river before it reaches a peaceful forest valley.



In this post we will review how to limit HTTP request body size in Go using http.MaxBytesReader. We will handle requests with a known Content-Length, requests whose length is unknown, and gzip requests that become much larger after decompression.

A small API can still receive a very large request. If the application reads that request into memory without a limit, one client can consume resources intended for many users. With enough concurrent requests, the result can be an out-of-memory failure and a restarting pod.

The important question is where we enforce the limit. Checking a header is useful, but the application must also limit the bytes it actually reads.

The Content-Length Problem

Assume our API accepts JSON documents up to one MiB, or 1,048,576 bytes.

A tempting implementation is:

if request.ContentLength > maxBodyBytes {
    http.Error(writer, "request body too large", http.StatusRequestEntityTooLarge)
    return
}

This can reject a known oversized request before parsing it. However it is not sufficient by itself.

An HTTP/1.1 client can send a body using chunked transfer encoding, without a Content-Length header. In Go, an unknown request body length is represented by ContentLength equal to -1. HTTP/2 requests can also arrive without a known length, although HTTP/2 does not use HTTP/1.1 chunked transfer encoding.

A negative length passes the check above. If we then call io.ReadAll(request.Body), the application continues allocating memory while the client sends data.

The limit must apply to the reader, including when the length is unknown.

Use http.MaxBytesReader

Go provides a standard library helper for this purpose:

request.Body = http.MaxBytesReader(writer, request.Body, maxBodyBytes)

The replacement reader reports a *http.MaxBytesError when reading would exceed the configured limit. We can identify that error with errors.As and return HTTP 413 Content Too Large.

Wrapping the reader does not load the body or check it immediately. The limit is enforced as downstream code reads it.

This distinction matters. If a handler reads only the first few bytes, it has not established that the entire body fits. If an endpoint requires a complete document, read and validate the complete bounded document before performing its business operation.

Also notice that io.LimitReader is a different tool. It returns EOF at its limit, which can make a truncated input look like a complete input. A size check built with it normally needs to allow one extra byte and explicitly detect overflow. MaxBytesReader provides the HTTP-specific error directly.

Gzip Changes What We Need to Count

Assume a client compresses a large JSON document before sending it. The compressed body could be small enough to pass an ingress limit while the decompressed document is far above the API's allowed size.

For a gzip request, Content-Length describes the compressed representation. It does not tell us how many bytes the application will receive from the gzip reader.

Go's HTTP server does not automatically decompress a request just because it has Content-Encoding: gzip. Our code or framework middleware must do that explicitly.

For an API that accepts compressed input, use two limits:

incoming body
    -> compressed/input byte limit
    -> gzip decompression, when requested
    -> decompressed byte limit
    -> parsing
    -> business operation

The input limit bounds bytes read before decompression. The decompressed limit bounds bytes delivered to the application after expansion. They can have different values.

For an uncompressed request, the same sequence works without the decompression step.

A Complete Go Example

The following server accepts one JSON document at POST /document. It supports an absent Content-Encoding or a single gzip encoding, and rejects other encodings with HTTP 415.

The example uses only the standard library. Save the following as main.go.

package main

import (
    "compress/gzip"
    "encoding/json"
    "errors"
    "flag"
    "io"
    "log"
    "net/http"
    "strings"
    "time"
)

type document struct {
    MessageText string `json:"message"`
}

type bodyLimits struct {
    inputBytes   int64
    decodedBytes int64
}

func (b *bodyLimits) readBody(
    writer http.ResponseWriter,
    request *http.Request,
) ([]byte, error) {
    request.Body = http.MaxBytesReader(writer, request.Body, b.inputBytes)
    defer request.Body.Close()

    var reader io.Reader = request.Body
    if strings.EqualFold(strings.TrimSpace(request.Header.Get("Content-Encoding")), "gzip") {
        compressed, err := gzip.NewReader(request.Body)
        if err != nil {
            return nil, err
        }
        defer compressed.Close()
        reader = compressed
    }

    decoded := http.MaxBytesReader(writer, io.NopCloser(reader), b.decodedBytes)
    defer decoded.Close()
    return io.ReadAll(decoded)
}

func writeReadError(
    writer http.ResponseWriter,
    err error,
) {
    var limitError *http.MaxBytesError
    if errors.As(err, &limitError) {
        http.Error(writer, "request body too large", http.StatusRequestEntityTooLarge)
        return
    }
    http.Error(writer, "cannot read request body", http.StatusBadRequest)
}

func (b *bodyLimits) handleDocument(
    writer http.ResponseWriter,
    request *http.Request,
) {
    if request.Method != http.MethodPost {
        writer.Header().Set("Allow", http.MethodPost)
        http.Error(writer, "method not allowed", http.StatusMethodNotAllowed)
        return
    }
    encodings := request.Header.Values("Content-Encoding")
    encoding := strings.TrimSpace(request.Header.Get("Content-Encoding"))
    if len(encodings) > 1 || (encoding != "" && !strings.EqualFold(encoding, "gzip")) {
        http.Error(writer, "unsupported content encoding", http.StatusUnsupportedMediaType)
        return
    }
    if request.ContentLength > b.inputBytes {
        http.Error(writer, "request body too large", http.StatusRequestEntityTooLarge)
        return
    }

    data, err := b.readBody(writer, request)
    if err != nil {
        writeReadError(writer, err)
        return
    }
    var value document
    if err := json.Unmarshal(data, &value); err != nil {
        http.Error(writer, "invalid JSON document", http.StatusBadRequest)
        return
    }

    // Perform the business operation only after reading and validating the body.
    writer.WriteHeader(http.StatusNoContent)
}

func main() {
    inputBytes := flag.Int64("max-input-bytes", 1<<20, "maximum input body bytes")
    decodedBytes := flag.Int64("max-decoded-bytes", 1<<20, "maximum decompressed body bytes")
    flag.Parse()
    if *inputBytes <= 0 || *decodedBytes <= 0 {
        log.Fatal("body limits must be positive")
    }
    limits := &bodyLimits{inputBytes: *inputBytes, decodedBytes: *decodedBytes}
    mux := http.NewServeMux()
    mux.HandleFunc("/document", limits.handleDocument)
    server := &http.Server{
        Addr:              "127.0.0.1:8080",
        Handler:           mux,
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       15 * time.Second,
        WriteTimeout:      15 * time.Second,
        IdleTimeout:       60 * time.Second,
    }
    log.Fatal(server.ListenAndServe())
}

Run the server:

go run main.go -max-input-bytes 1048576 -max-decoded-bytes 1048576

The Content-Length check is an early rejection for the input limit. The readers enforce the actual limits for known and unknown lengths.

Reading through the decompressed reader to EOF also checks that a gzip stream finishes correctly. A malformed or truncated stream returns HTTP 400. If either reader reports MaxBytesError, the response is HTTP 413.

json.Unmarshal checks the complete buffered document, so a valid JSON object followed by another object or unexpected trailing data is rejected. Ordinary trailing JSON whitespace is accepted, but still counts toward the byte limit.

Notice that the handler does not send success before reading the body. Once a response has started, changing its status may be too late. This is also discussed in HTTP Streaming Error Handling in GO: Why HTTP 200 Is Not Enough

Try Small and Oversized Requests

A small document should return HTTP 204:

curl -i -H 'Content-Type: application/json' \
    --data-binary '{"message":"hello"}' \
    http://127.0.0.1:8080/document

Create a JSON document with a two-MiB message:

python3 - <<'PY'
import json
with open("large.json", "w") as output:
    json.dump({"message": "x" * (2 * 1024 * 1024)}, output)
PY

Send it with its known length:

curl -i -H 'Content-Type: application/json' \
    --data-binary @large.json \
    http://127.0.0.1:8080/document

The server should return HTTP 413. To exercise HTTP/1.1 chunked input, send the same document without Content-Length:

curl --http1.1 -i \
    -H 'Content-Type: application/json' \
    -H 'Transfer-Encoding: chunked' -H 'Content-Length:' \
    --data-binary @large.json \
    http://127.0.0.1:8080/document

The reader still rejects it. Chunk boundaries do not reset the byte counter.

Now compress the document:

gzip -c large.json > large.json.gz
wc -c large.json large.json.gz

Send the compressed version:

curl -i -H 'Content-Type: application/json' \
    -H 'Content-Encoding: gzip' \
    --data-binary @large.json.gz \
    http://127.0.0.1:8080/document

Although this repetitive document compresses very well, the decompressed limit should still produce HTTP 413.

Middleware Order and Error Handling

In a framework such as Echo, place the input limit before request decompression and the decoded limit after it. Check the framework's actual execution order: middleware registration order alone can be misleading when wrappers are nested.

Both limits must run before body logging, parsing, or any other component that buffers the body. A limiter installed after io.ReadAll cannot undo the allocation.

Also make sure size errors survive the framework's error handling. A parser that converts every read error into a string can lose the MaxBytesError type. The application might then return HTTP 400 or 500 instead of 413.

Preserve wrapped errors where possible. If an existing abstraction cannot preserve them, the limiting reader can record that overflow occurred, and the handler boundary can inspect that state before writing its response. Do not identify overflow by matching an error message.

The sample keeps error handling directly beside the read, so it does not need that extra state.

A Body Limit Is One Part of the Memory Budget

The example buffers a bounded body for simplicity. This does not mean that one MiB of accepted JSON requires only one MiB of memory.

The buffer can have spare capacity. JSON decoding creates additional values, and request handling retains other state. Multiple simultaneous requests multiply those costs.

Keep the maximum request size configurable, choose limits for each endpoint's real needs, and also bound active requests and waiting work. I covered that part in Go Concurrency Limits: Prevent Goroutine Explosions with Backpressure

Streaming parsing can reduce buffering for large documents, but it still needs byte limits, validation, and a clear decision about when side effects are allowed. One successful json.Decoder.Decode call does not prove the body ended; a single-document API must also check what follows.

If you need to understand which JSON fields consume the space, see JSON Size Analysis

Size Limits and Deployment Limits

An ingress or reverse proxy body limit is useful because it can reject traffic before it reaches the service. Keep application limits as well: internal callers may reach the service directly, and a proxy might only see the compressed representation.

A byte limit does not impose a time limit. A client can send an allowed body very slowly. The example includes server timeouts; production values should reflect expected request sizes, upload speeds, and proxy behavior. Decompression also consumes CPU, so byte limits do not replace concurrency control or protection at the network edge.

For multipart uploads, apply an overall body limit before parsing, then add the required file and field limits. A multipart memory threshold alone is not a total upload-size limit; parsers can spill file data to disk.

Monitor 413 responses by endpoint and check that valid clients still fit. Avoid logging complete rejected bodies, which creates another resource problem and can expose sensitive data.

Verify the Boundaries

Before using the limit, check an empty body, valid small JSON, malformed JSON, and valid JSON followed by a second document. Check a body exactly at the limit and another one byte above it.

Repeat the size cases with known lengths, unknown lengths, and gzip input. Check truncated gzip data and unsupported Content-Encoding values. For oversized input, verify HTTP 413 and verify that the business operation never runs.

If a reader or middleware changes, repeat these checks through the actual handler chain. Testing a size helper in isolation will not catch a decompression layer or error wrapper installed in the wrong place.

Final Note

Use Content-Length for an early rejection, then enforce the real limit while reading. If requests can be compressed, bound both the incoming representation and the decompressed content.

Read and validate the required document before performing its operation, preserve size errors through middleware, and combine request limits with concurrency and time limits. This gives an API a predictable response to oversized input instead of an unpredictable memory failure.

Monday, November 2, 2026

Atomic File Writes in Go: Prevent Corrupted Files After a Crash

A complete replacement document is prepared beside protected storage, illustrating atomic file replacement in Go.



In this post we will review how to save a file in Go without leaving a partially written version when the process crashes. We will use a temporary file and an atomic rename, then explain the additional synchronization needed when the entire machine fails.

This is useful for JSON state files, configuration snapshots, and checkpoints. A file can be small and still be important: if the application cannot read it after restarting, a failed save can become a startup failure.

The examples target Linux and a local filesystem that supports atomic replacement and directory synchronization. The application owns the destination directory, and one writer controls the state being saved.

The Overwrite Problem

Assume our application stores its last processed record in state.json:

{"last_processed_id":100}

After more work, it needs to save 200. The obvious implementation is:

err := os.WriteFile("state.json", data, 0o600)

For an existing file, os.WriteFile truncates it before writing the replacement. If the process stops between these operations, the original content is already gone. If writing fails partway through, the file can contain incomplete JSON.

Checking the returned error is necessary, but it cannot restore the previous file. A sudden process termination also gives our code no opportunity to handle the error.

The Go documentation describes this partial-write behavior.

Reproduce an Interrupted Save

Create a disposable directory and run the examples there. First create a valid state file:

printf '{"last_processed_id":100}\n' > state.json

Save the following program as unsafe.go:

package main

import (
	"log"
	"os"
)

func main() {
	file, err := os.Create("state.json")
	if err != nil {
		log.Fatal(err)
	}
	if _, err := file.WriteString("{\"last_processed_id\":"); err != nil {
		log.Fatal(err)
	}
	os.Exit(1)
}

Run it:

go run unsafe.go
cat state.json

The program deliberately exits with an error after writing only the beginning of the document. The file now contains:

{"last_processed_id":

This is a controlled demonstration of an interrupted overwrite. It does not simulate a power failure, but it makes the application-level problem reproducible without waiting for a real crash.

Notice that defer would not fix this. Deferred functions do not run when the process is killed with SIGKILL or exits through os.Exit.

Prepare the New File Before Replacing the Old One

Instead of changing the current file, prepare its replacement separately:

  1. Serialize the complete state in memory.
  2. Create a uniquely named temporary file in the destination directory.
  3. Write the new content to that file.
  4. Synchronize and close it.
  5. Rename it over the destination.
  6. Synchronize the directory.

Until the rename, state.json remains untouched. On the Linux filesystem assumed here, a reader opening that path sees the old complete file or the new complete file. A reader that already has the old file open can continue reading it.

The temporary file must be on the same filesystem as the destination. Creating it in the destination directory is the simplest way to arrange this. Using the default temporary directory could put it on another filesystem, where the rename fails.

Do not delete the destination before renaming. That would introduce a period where the file is missing and discard the old copy before replacement succeeds.

The Linux rename documentation describes the replacement behavior.

Atomic Replacement and Durability

There are two separate requirements here.

Atomic replacement controls what readers observe while the system is running. They should never open a half-written replacement through the destination path.

Durability concerns what survives a machine crash or power loss. A successful write or close can leave data in operating-system caches. A rename alone does not establish that both the new content and its directory entry reached persistent storage.

The Linux sequence used here is:

write temporary file
sync temporary file
close temporary file
rename temporary file to destination
sync destination directory

The file sync requests persistence of its content and metadata. The directory sync requests persistence of the name change. Both operations can fail, and their errors must be handled.

This is the standard persistence sequence for this Linux use case, subject to the filesystem and storage stack honoring these operations. It does not protect against failing hardware or replace backups.

The Linux fsync documentation explains why the directory requires its own synchronization.

Go Implementation

The following program uses only the standard library and requires Go 1.20 or later because it uses errors.Join. Save it as main.go and run it separately from unsafe.go:

package main

import (
	"errors"
	"fmt"
	"log"
	"os"
	"path/filepath"
)

func writeFileAtomic(
	filePath string,
	data []byte,
) error {
	directory := filepath.Dir(filePath)
	temporary, err := os.CreateTemp(directory, ".state-*.tmp")
	if err != nil {
		return fmt.Errorf("create temporary file: %w", err)
	}
	defer temporary.Close()
	defer func() {
		err := os.Remove(temporary.Name())
		if err != nil && !errors.Is(err, os.ErrNotExist) {
			log.Printf("remove temporary file: %v", err)
		}
	}()

	if _, err := temporary.Write(data); err != nil {
		return fmt.Errorf("write temporary file: %w", err)
	}
	if err := temporary.Sync(); err != nil {
		return fmt.Errorf("sync temporary file: %w", err)
	}
	if err := temporary.Close(); err != nil {
		return fmt.Errorf("close temporary file: %w", err)
	}
	if err := os.Rename(temporary.Name(), filePath); err != nil {
		return fmt.Errorf("replace destination: %w", err)
	}
	if err := syncDirectory(directory); err != nil {
		return fmt.Errorf("destination replaced, directory sync failed: %w", err)
	}
	return nil
}

func syncDirectory(
	directory string,
) error {
	file, err := os.Open(directory)
	if err != nil {
		return err
	}
	syncError := file.Sync()
	closeError := file.Close()
	return errors.Join(syncError, closeError)
}

func main() {
	data := []byte("{\"last_processed_id\":200}\n")
	if err := writeFileAtomic("state.json", data); err != nil {
		log.Fatal(err)
	}
	fmt.Println("Saved state.json")
}

Run the safe version:

go run main.go
cat state.json

The destination now contains:

{"last_processed_id":200}

os.CreateTemp creates a unique file with restrictive permissions, 0o600 before applying the process umask. This example retains those permissions when the file becomes state.json.

The deferred close is a fallback for early failures. The explicit close before rename is checked. Deferred removal cleans up an unpublished temporary file during a normal return; after a successful rename, the temporary pathname no longer exists.

The helper expects the parent directory to exist and remain stable during the operation. Create the application's state directory during initialization. Persisting a newly created directory hierarchy requires additional synchronization of its parent directories.

What Happens at Each Failure Point?

If the temporary write, file sync, or close fails, the rename does not happen. An existing destination remains unchanged.

If the process stops before rename, an existing destination still contains the old version. A temporary file may remain because deferred cleanup did not run.

If rename succeeds, new opens of the destination see the replacement. If the process then stops before directory synchronization, its persistence across a later machine failure has not been established.

If directory synchronization fails, the function returns an error that explicitly says the destination was already replaced. We cannot treat every error as meaning that nothing changed. The new version is visible, but its durability was not confirmed.

On the first save there is no old version to preserve. A process interruption before rename leaves the destination absent, possibly alongside an unfinished temporary file.

These distinctions matter when deciding whether to retry or report success. A checkpoint should also be coordinated with the work it represents; safely writing the file does not make an external side effect and the checkpoint one transaction.

The same uncertainty appears when a connection breaks after a server has performed its work, as discussed in HTTP Streaming Error Handling in GO: Why HTTP 200 Is Not Enough.

Verify the Failure Paths

Reset state.json to 100. In a disposable copy of main.go, insert os.Exit(1) immediately before os.Rename and run it again.

state.json should still contain 100. The completed temporary file should remain beside it. Repeat with an exit after writing only part of the temporary content: the destination should still be unchanged.

Remove the injected exit and run the normal version. The destination should contain 200, and the operation should leave no temporary file behind.

Also check a failed rename and a failed directory sync. The first should preserve the existing destination. The second should report an error while leaving the new content visible.

These checks verify the process-interruption behavior. They do not prove recovery after a power loss; that requires testing the actual filesystem and storage environment with an appropriate crash-testing setup.

Permissions and Concurrent Writers

Replacing a file installs a new filesystem object. It does not automatically preserve the old file's permissions, ownership, ACLs, or extended attributes. If specific metadata is required, apply it to the temporary file before its sync and publication.

The example also assumes the destination is a regular state-file path, not a symbolic link whose target must be updated. Renaming onto a symbolic link replaces that link itself.

Unique temporary names prevent writers from sharing the same temporary file. They do not prevent lost updates.

Assume two workers read 100, independently calculate 101, and each publish a complete file. Both files are valid, but one update is lost. Within one process, serialize the entire read-modify-write operation. Across processes, use appropriate coordination or a transactional database.

This is related to the distinction between individual atomic operations and a complete synchronized operation discussed in Go Atomic Value is NOT sync.

Operational Limits

A replacement temporarily needs space for both versions. Near a disk limit, even a small state update can fail during writing or synchronization. Keep the old version and surface the failure instead of continuing as if the state was saved.

Abrupt exits can leave temporary files. If startup cleanup removes them, ensure no active writer can still own them; a broad filename match alone is not sufficient.

Go does not promise atomic os.Rename behavior on every operating system. Windows, network filesystems, container volume drivers, and object-storage mounts require checking their own replacement and persistence semantics. Do not infer those guarantees from a successful test on a local Linux directory.

For several files that must change together, atomic replacement of each file separately is insufficient. Use a transactional store or a publication scheme that switches one reference to a complete version.

When the state already belongs in PostgreSQL, a database transaction can also keep a business update and its queued work together, as shown in Build a PostgreSQL Job Queue with SKIP LOCKED.

Final Note

For a small state file, the useful pattern is straightforward: prepare the complete replacement, sync and close it, publish it with a same-filesystem rename, then sync the directory when durability is required.

This keeps an interrupted save from destroying the last complete version and makes the remaining boundaries explicit: persistence, concurrent updates, and recovery after an uncertain result.