Cloud Computing

Cloud-Native and the Twelve-Factor App: What Each Factor Means for a Container

Intermediate10 min readUpdated

The twelve-factor methodology is still the shortest useful description of an application that a scheduler can run. This guide translates each factor into concrete decisions for a containerised Spring Boot service, shows the configuration and lifecycle code that implements them, and then covers the four areas — secrets, observability, health, resilience — where a 2011 checklist no longer suffices.

What you will learn

  • Explain each of the twelve factors and what it forbids as well as what it requires
  • Externalise configuration and secrets correctly for a containerised service
  • Make a process stateless, disposable and safe to kill at any moment
  • Treat logs as an event stream and stop writing to files inside containers
  • Identify where the twelve-factor model is incomplete and what to add alongside it

The twelve-factor methodology was published in 2011 by engineers at a platform-as-a-service company who had watched thousands of applications either thrive or fall over on their infrastructure. It is a list of properties an application needs in order to be started, stopped, replicated and moved by something other than a human. Fifteen years later the platforms have changed completely and the list has barely dated, because the underlying question has not: can a scheduler run more copies of this, kill one at random, and move them to a different machine without anyone noticing?

This guide takes each factor and asks what it means concretely for a containerised service — the examples assume a Spring Boot application running on Kubernetes, but nothing here is framework-specific. It then spends the last third on the parts the original document does not cover, because a service that satisfies all twelve factors and nothing else is not production-ready in 2026.

Codebase, dependencies, configuration

I. Codebase — one codebase tracked in version control, many deploys. One application maps to one repository. The same commit is deployed to staging and production; what differs between them is configuration, never the code. Two applications sharing a codebase is a distributed monolith waiting to happen; one application spread across two repositories cannot be released atomically. Shared code belongs in a library with its own version number.

II. Dependencies — declare and isolate them. Every dependency is listed explicitly with a version, and nothing is assumed to exist on the host. In practice this means a build file that pins versions, a lock file or dependency-verification metadata committed alongside it, and a container image that carries the runtime rather than expecting one. The isolation half matters as much as the declaration: a build that succeeds only because a tool happens to be installed on the developer's machine will fail in the pipeline, and a container image that inherits latest from a base image is not reproducible.

III. Config — store configuration in the environment. The test the original document proposes is still the best one: could you open-source the repository right now without leaking any credential? Configuration is everything that varies between deploys — database URLs, credentials, feature flags, the address of an upstream service, log levels. It does not include things that are the same everywhere, such as internal routing tables, which are code.

For a Spring Boot service this means relying on the standard property-resolution order and letting the platform supply the values:

# application.yaml — defaults only, no environment values, no secrets
spring:
  application:
    name: orders-api
  datasource:
    url: ${DB_URL}
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}
  jpa:
    hibernate:
      ddl-auto: none
server:
  shutdown: graceful
management:
  endpoints:
    web:
      exposure:
        include: health,info,prometheus

Avoid the trap of encoding environments into the artifact. A profile called prod inside the image means the image now knows which environment it is in, and the "many deploys, one build" property is gone. Profiles are acceptable for behavioural variants (kubernetes, local); environment-specific values belong outside.

Backing services, build/release/run, processes

IV. Backing services — treat them as attached resources. A database, a cache, a message broker, an SMTP relay and a third-party API are all the same kind of thing: something reachable at a URL with credentials. Swapping a locally managed PostgreSQL for a managed one should be a configuration change and nothing else. The corollary is that your code should not special-case whether a dependency is local, and should not embed assumptions such as a filesystem path shared with the database host.

V. Build, release, run — separate the stages strictly. The build turns source into an immutable artifact (a container image, identified by digest). The release combines that artifact with a specific configuration set and gets an identifier of its own. The run executes a release. Two rules follow: releases are immutable — you never patch a running container, you create a new release — and every release is individually addressable, which is what makes rollback a one-line operation. Editing a file inside a running pod breaks this, and the change disappears at the next restart anyway.

VI. Processes — execute the app as one or more stateless, share-nothing processes. Anything a process keeps in memory or on local disk must be treated as a cache that can vanish at any moment. The usual offenders are HTTP session state, in-memory rate-limit counters, uploaded files written to a local directory, and scheduled jobs that assume exactly one instance is running.

The fixes are well established: put session state in Redis or make the session a signed token, use a shared store for counters, write uploads to object storage, and coordinate scheduled work through a distributed lock or a scheduler that guarantees single execution. Sticky sessions are a workaround, not a solution — they defeat even load distribution and turn a pod eviction into a user-visible logout.

Port binding, concurrency, disposability

VII. Port binding — export services via port binding. The application is self-contained and listens on a port it is told about; it is not deployed into an external application server that provides the HTTP runtime. Spring Boot's embedded server does exactly this, which is why the executable JAR model displaced WAR deployment for cloud workloads. A twelve-factor process can also be a backing service for another process, reached at a host and port.

VIII. Concurrency — scale out via the process model. Scale by running more processes, not by growing one. Different workload types become different process types with independent scaling: a web process type sized against request rate, a worker process type sized against queue depth, and never both inside one deployment sharing a thread pool. Vertical scaling has a ceiling and does not improve availability; horizontal scaling improves both, provided factor VI holds.

IX. Disposability — maximise robustness with fast startup and graceful shutdown. This is the factor most often failed in practice, and it is entirely about lifecycle behaviour.

Fast startup matters because it bounds how quickly the platform can react to load or reschedule after a node failure. Slow context initialisation, eager connection-pool warming and classpath scanning all add to it; class-data sharing, ahead-of-time compilation and trimming autoconfiguration are the usual levers.

Graceful shutdown matters more. When a container is stopped, the platform sends SIGTERM, waits a grace period, then sends SIGKILL. The application must stop accepting new work, finish what it has, close connections and exit before the grace period expires. On Kubernetes there is an ordering subtlety that causes a great deal of confusion: pod deletion and endpoint removal happen concurrently, so a pod can receive requests for a short window after SIGTERM. A brief pre-stop sleep gives the routing layer time to catch up.

spec:
  terminationGracePeriodSeconds: 45
  containers:
    - name: orders-api
      image: registry.example.com/orders-api@sha256:9f2c...
      lifecycle:
        preStop:
          exec:
            command: ["sh", "-c", "sleep 5"]
      readinessProbe:
        httpGet: { path: /actuator/health/readiness, port: 8080 }
        periodSeconds: 5
      livenessProbe:
        httpGet: { path: /actuator/health/liveness, port: 8080 }
        periodSeconds: 10
        failureThreshold: 3

Also required by this factor: workers must be robust against sudden death. A job pulled from a queue and lost when the process dies means the queue's visibility-timeout and redelivery semantics must be configured, and the handler must be idempotent because redelivery will happen.

FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
COPY target/orders-api.jar app.jar
USER 1000
EXPOSE 8080
# exec form: the JVM becomes PID 1 and receives SIGTERM directly
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]

The shell form of ENTRYPOINT wraps the process in /bin/sh, which does not forward signals; the JVM then never sees SIGTERM and is killed abruptly at the end of the grace period. It is a one-word mistake that silently disables graceful shutdown, and it is extremely common. More container packaging detail is in Docker fundamentals.

Parity, logs, admin processes

X. Dev/prod parity — keep development, staging and production similar. Three gaps are named in the original: time (how long between writing code and running it in production), personnel (whether the author deploys it) and tools (whether the backing services differ). Substituting an in-memory database for the production engine is the classic tools gap and it hides everything interesting — dialect differences, isolation-level behaviour, index usage. Containers largely solved this: run the real engine locally, and use the same image everywhere.

XI. Logs — treat logs as event streams. The application writes to standard output, unbuffered, and knows nothing about files, rotation or destinations. The platform collects the stream and routes it to a log aggregation system. Writing to a file inside a container means the logs vanish with the container and consume the writable layer until it fills.

Emit structured JSON with correlation identifiers so that the aggregator can index fields rather than parse text:

{"timestamp":"2026-09-07T09:14:22.118Z","level":"WARN","service":"orders-api",
 "traceId":"4bf92f3577b34da6a3ce929d0e0e4736","spanId":"00f067aa0ba902b7",
 "message":"payment authorisation retried","orderId":"A-91245","attempt":2}

XII. Admin processes — run one-off tasks as one-off processes. Database migrations, data fixes and report generation run against the same release, from the same codebase, with the same configuration — as a job on the platform, not as an SSH session on a host. Schema migration tools invoked at startup or as an init container satisfy this; a document of SQL statements someone runs by hand does not, because it is not versioned, reviewed or repeatable.

What the twelve factors do not cover

Satisfying all twelve gets an application scheduled reliably. It does not make it operable. Four gaps matter enough to treat as additional factors.

Secrets are not just config. Factor III lumps a feature flag and a database password together, and that has not aged well. Secrets need rotation without redeployment, an audit trail of access, encryption at rest with a key you control, and a blast radius limited to one workload. The pattern that satisfies all of those: the workload authenticates to the platform with an identity it did not have to store — an IAM role or a managed identity — and fetches secrets from a managed store at startup, refreshing periodically. Nothing sensitive is in the image, the manifest, the repository or the environment block.

Observability is not just logs. Factor XI covers one of three signals. A service that can be operated also emits metrics (rate, errors, duration, saturation, plus business counters) and distributed traces with context propagated across service boundaries. OpenTelemetry is the vendor-neutral standard for all three and is the practical default; the application-side setup is covered in Actuator and observability.

Health is not a single boolean. The platform needs at least three distinct answers: is the process alive and worth keeping (liveness), is it able to serve traffic right now (readiness), and has it finished its slow initial startup (startup). Conflating liveness with readiness is the source of a well-known failure mode where a temporarily unavailable dependency causes every replica to be killed and restarted in a loop, turning a partial degradation into a total outage. Liveness should test only the process itself.

Resilience and API contracts. Timeouts, retries with jitter, circuit breakers, backpressure and rate limits are architectural properties the methodology never mentions, as are backward-compatible API evolution and schema migrations that are safe to run while both the old and new release are live. The expand-then-contract migration pattern — add a nullable column, deploy code that writes both, backfill, deploy code that reads the new column, drop the old one — is what makes factor V's instant rollback actually safe.

The CNCF's definition of cloud-native captures the wider ambition: loosely coupled systems that are resilient, manageable and observable, combined with automation that lets engineers make high-impact changes frequently and predictably. The twelve factors are how an individual process earns its place in such a system; they are the entry requirement, not the whole design, which is why they sit alongside the broader concerns in microservices architecture.

A short audit for an existing service

Run these questions against a service you already operate. Each "no" is a concrete ticket.

  1. Can the repository be made public today without leaking a credential?
  2. Is the deployed artifact identified by an immutable digest, and is the same digest in staging and production?
  3. If two replicas run and one is killed mid-request, does any user lose data or a session?
  4. Does the process exit cleanly within the grace period after SIGTERM, with in-flight requests completed?
  5. Does the container write anything to local disk that is not a genuine cache?
  6. Are logs on standard output, structured, and carrying a trace identifier?
  7. Do liveness and readiness check genuinely different things?
  8. Can a secret be rotated without rebuilding the image?
  9. Do migrations run as a versioned job against the same release, and are they compatible with the previous release?
  10. Is startup fast enough that autoscaling reacts before the traffic spike has passed?

Key takeaways

  • The twelve factors describe the contract between an application and a scheduler: one codebase, declared dependencies, externalised config, attached backing services, and strict separation of build, release and run.
  • Statelessness and disposability carry most of the practical weight — no local session state, no local files, fast startup, and a graceful shutdown that actually receives SIGTERM.
  • Configuration belongs outside the artifact so that a single immutable image runs unchanged in every environment; environment-named build profiles quietly break that property.
  • Logs are an unbuffered structured stream to standard output, routed by the platform, never files inside a container.
  • The methodology is a baseline, not a complete definition: add managed secrets with platform identity, full observability, distinct health signals, and explicit resilience and migration strategies.

Sources and further reading

Frequently asked questions

Is the twelve-factor methodology outdated?
The factors themselves have aged well because they describe the contract between an application and a scheduler, and that contract has not changed. What has changed is the scope: the methodology says almost nothing about secrets management, distributed tracing, health probes, retries, service discovery or autoscaling, all of which are now table stakes. Treat it as a necessary baseline rather than a complete definition of cloud-native.
How do secrets fit the config factor if environment variables are risky?
The factor's real requirement is that configuration lives outside the code and varies by deployment, not that it must be an environment variable. Environment variables leak into crash dumps, process listings, child processes and log lines, and cannot be rotated without a restart. Fetch secrets at startup from a managed secret store using the workload's own platform identity, or have the platform project them into a mounted file, and cache them with a refresh interval.
Can a database or a message broker be twelve-factor?
No, and it does not need to be. The methodology describes stateless application processes; stateful systems deliberately break several factors, particularly disposability and share-nothing concurrency. In a twelve-factor architecture those systems are backing services attached by URL. Running them yourself on a scheduler is possible with operators and volume claims, but you are then operating a database, not writing a twelve-factor app.
What does dev/prod parity mean when production has forty services?
It means the gaps that matter are closed: same backing-service technologies and major versions, same container image, same configuration mechanism, and hours rather than weeks between writing code and running it in production. It does not mean every developer runs the whole estate locally, which stops being feasible past a handful of services. Containers for the immediate dependencies plus a shared, cheap, ephemeral integration environment is the usual answer.