Twelve-Factor App and cloud native

Mid-level Frequently asked 5 min

On this page

The question

What is a cloud-native application?

30-second answer

An application designed to run on elastic, automated infrastructure rather than on a few long-lived servers. In practice it is split into services packaged as containers, runs as stateless, disposable processes that scale out, gets its config from the environment, uses managed backing services, is deployed by an automated pipeline, and is observable through logs, metrics and traces. The Twelve-Factor App, written by Heroku engineers, is the classic checklist for the application side of it.

Understand it

The twelve factors on a running service

Tap the parts

Select a part to see what it does.

Tap a part. The left column is how the service is built and shipped, the right how it runs; together the nine parts cover all twelve factors.

View as text

Two columns of parts on one service. Build and ship: build, release, config and parity. Run: processes, port, backing services, disposability and logs. Each part names the factors it shows, numbered I to XII.

Build, factors 1 and 2: One repository per service, deployed many times.

Release, factors 5 and 12: Build once, then release: the artifact plus one environment’s config, immutable and numbered, so rollback picks an old release.

Config, factors 3: Everything that differs between environments, URLs, credentials, feature flags, comes from the environment, never from code or a file baked per environment.

Parity, factors 10: Keep development, staging and production alike: the same image, the same backing services, such as PostgreSQL through Testcontainers rather than H2, and deploys hours after a change, not weeks.

Processes, factors 6 and 8: The app runs as stateless processes that share nothing: sessions, uploads and caches that matter live in backing services.

Port, factors 7: The service is self-contained and exports HTTP by binding a port, with its embedded server, such as Tomcat in a Spring Boot jar.

Backing, factors 4: Databases, queues, caches and mail services are attached resources, located by URL and credentials in config.

Dispose, factors 9: Processes start fast and stop gracefully: on SIGTERM they stop taking work, finish what is in flight and exit.

Logs, factors 11: The app writes its log as an event stream to stdout, one event per line, ideally JSON.

Two columns of parts on one service. Build and ship: build, release, config and parity. Run: processes, port, backing services, disposability and logs. Each part names the factors it shows, numbered I to XII.

Build, factors 1 and 2: One repository per service, deployed many times.

Release, factors 5 and 12: Build once, then release: the artifact plus one environment’s config, immutable and numbered, so rollback picks an old release.

Config, factors 3: Everything that differs between environments, URLs, credentials, feature flags, comes from the environment, never from code or a file baked per environment.

Parity, factors 10: Keep development, staging and production alike: the same image, the same backing services, such as PostgreSQL through Testcontainers rather than H2, and deploys hours after a change, not weeks.

Processes, factors 6 and 8: The app runs as stateless processes that share nothing: sessions, uploads and caches that matter live in backing services.

Port, factors 7: The service is self-contained and exports HTTP by binding a port, with its embedded server, such as Tomcat in a Spring Boot jar.

Backing, factors 4: Databases, queues, caches and mail services are attached resources, located by URL and credentials in config.

Dispose, factors 9: Processes start fast and stop gracefully: on SIGTERM they stop taking work, finish what is in flight and exit.

Logs, factors 11: The app writes its log as an event stream to stdout, one event per line, ideally JSON.

Takeaway: A twelve-factor service is built once, configured by its environment, runs as stateless, disposable processes behind a port, treats databases as attached resources and writes logs to stdout.

The twelve factors along a service's life, from commit to logsOne codebase with declared dependencies is built once into an artifact. The artifact plus one environment's config makes an immutable release, and one-off admin tasks run from that release. The release runs as stateless processes that bind a port, scale out by adding processes, use backing services attached by URL, start fast and stop gracefully, and write logs to stdout. Development, staging and production stay alike.I Codebase,II DependenciesBuild once:orders:3f9c2e1V Release =artifact + III ConfigXII Admin tasks:same releaseVI Statelessprocesses,VIII scaled outVII Port binding::8080IV Backing services:by URLIX Fast start,graceful stopXI Logs to stdoutX Same image indev, staging, prod
The twelve factors along a service's life, from commit to logsOne codebase with declared dependencies is built once into an artifact. The artifact plus one environment's config makes an immutable release, and one-off admin tasks run from that release. The release runs as stateless processes that bind a port, scale out by adding processes, use backing services attached by URL, start fast and stop gracefully, and write logs to stdout. Development, staging and production stay alike.I Codebase,II DependenciesBuild once:orders:3f9c2e1V Release =artifact + III ConfigXII Admin tasks:same releaseVI Statelessprocesses,VIII scaled outVII Port binding::8080IV Backing services:by URLIX Fast start,graceful stopXI Logs to stdoutX Same image indev, staging, prod
The twelve factors along a service's life, from commit to logs
Factor in practiceAWS (Amazon Web Services)AzureGCP (Google Cloud Platform)
III Config and secretsParameter Store, Secrets ManagerApp Configuration, Key VaultParameter Manager, Secret Manager
IV Backing servicesRDS (Relational Database Service), ElastiCacheAzure Database for PostgreSQL, Azure Cache for RedisCloud SQL, Memorystore
XI Logs as a streamCloudWatch LogsAzure Monitor LogsCloud Logging
XII One-off admin tasksECS (Elastic Container Service) run-taskContainer Apps jobsCloud Run jobs

In code

# Safe local defaults; production sets DATABASE_URL, DATABASE_USER and DATABASE_PASSWORD
spring.datasource.url=${DATABASE_URL:jdbc:postgresql://localhost:5432/orders}
spring.datasource.username=${DATABASE_USER:orders}
spring.datasource.password=${DATABASE_PASSWORD:orders}
payments.base-url=${PAYMENTS_URL:http://localhost:9090}
# Relaxed binding: an environment variable SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE=12 sets the pool size
spring.datasource.hikari.maximum-pool-size=10
III Config: defaults in the jar, every environment-specific value from the environment
# Wrong: files inside the container fill its disk and vanish with it
 Wrong logging.file.name=/var/log/orders/orders.log
# Right: one JSON event per line on stdout; the platform collects and routes it
 Right logging.structured.format.console=ecs
XI Logs: an event stream to stdout, not files the app manages
apiVersion: batch/v1
kind: Job
metadata:
  name: orders-migrate-3f9c2e1
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: registry.example.com/orders:3f9c2e1   # the release the app will run
          args: ["--spring.main.web-application-type=none", "--spring.flyway.enabled=true"]
          envFrom:
            - configMapRef: { name: orders-config }
            - secretRef: { name: orders-db }
XII Admin processes: run the migration as a one-off job from the same release
A release with a migration, admin task first, then the processesThe pipeline creates release 3f9c2e1 from the built image and production's config. It runs the migration as a one-off job from that release, which updates the database schema and exits. Only then does the platform replace the old processes with new ones from the same release; each old process receives SIGTERM, finishes its requests and exits.ProcessesPostgreSQLMigration jobPipelinerelease = image 3f9c2e1 + prod configrun once, same releaseapply V42 migrationexit 0start new processes from 3f9c2e1SIGTERM to old processesin-flight requests done, exit
A release with a migration, admin task first, then the processesThe pipeline creates release 3f9c2e1 from the built image and production's config. It runs the migration as a one-off job from that release, which updates the database schema and exits. Only then does the platform replace the old processes with new ones from the same release; each old process receives SIGTERM, finishes its requests and exits.ProcessesPostgreSQLMigration jobPipelinerelease = image 3f9c2e1 + prod configrun once, same releaseapply V42 migrationexit 0start new processes from 3f9c2e1SIGTERM to old processesin-flight requests done, exit
A release with a migration: admin task first, then the processes

Solve it

Make a legacy Spring service ready to run on Kubernetes

A Spring service is built three times, as orders-dev.war, orders-staging.war and orders-prod.war, each with its own prod.properties baked in. It runs in an application server, writes rolling log files to /var/log, stores uploads in /data, keeps sessions in memory, and someone runs SQL migrations by hand before each release. Plan the changes, factor by factor.

  1. One build, config outside. Build a single executable jar and image per commit; move every per-environment value into environment variables or mounted config (factors III and V). The same image then runs in dev, staging and production (X).
  2. Bind a port, drop the server. Package as a Spring Boot jar with embedded Tomcat that binds port 8080 (VII), so the container needs only a JRE (Java Runtime Environment) and the platform routes to the port.
  3. Make processes stateless. Move sessions to Redis and uploads to object storage, both attached by URL (IV and VI); then Kubernetes can run any number of replicas (VIII) and kill any one of them.
  4. Logs and lifecycle. Log JSON to stdout instead of files (XI). Turn on graceful shutdown and keep startup short, so a SIGTERM never drops a request (IX). Run migrations as a one-off job from the release (XII).
  5. Check. Deploy the same image to two environments with different variables; delete a Pod during a load test and see no failed request and no lost session; find the logs in the platform’s log search, not on a disk.
FROM eclipse-temurin:21-jre
COPY build/libs/orders.jar /app/orders.jar
USER 1000
EXPOSE 8080
# Configuration arrives as environment variables, so this image runs unchanged in dev, staging and production
# Graceful shutdown is the default from Spring Boot 3.4; older versions need it set
ENV SERVER_SHUTDOWN=graceful
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "/app/orders.jar"]
One image for every environment: no properties file baked in, port bound, java as process 1

How to answer

  • Cloud native is about how the app is built and run, not about which cloud it runs on.
  • Assume any instance can disappear at any time, and design so that it does not matter.
  • Automation, from tests to infrastructure as code, is part of the definition.
  • Spring Boot fits it well, with embedded servers, external config, Actuator and graceful shutdown.

Common mistakes

  • Calling an app cloud native because it runs on a virtual machine in a public cloud.
  • Equating cloud native with microservices or with Kubernetes.

Follow-up questions

Which of the twelve factors matter most, and why?

Config in the environment, so one artifact serves every environment and no secret sits in code. Build, release, run, so production runs exactly what was tested and rolls back by release. Stateless processes, so instances can scale and be replaced freely. Disposability, so deploys and scale-in drop no requests. Logs as event streams, so the platform collects them. Backing services as attached resources, so a database moves by changing a URL. The others support these six.

  • Each factor answers a concrete failure, such as lost sessions, drifting environments or full disks.
  • Map each to Spring Boot, such as external config, embedded server, graceful shutdown and stdout logging.
  • Newer practice adds telemetry, security and API-first design to the list.

See it in the infographic: The twelve factors on a running service

Why should configuration live in the environment instead of the code? How does Spring Boot support it?

Because the same artifact must run in every environment: building one per environment means production runs something never tested, and credentials in the repository leak. So the code holds safe defaults, and each environment provides URLs, credentials and flags as environment variables, mounted files or a config service. Spring Boot reads them in a fixed precedence, with environment variables above application.properties, and relaxed binding maps SPRING_DATASOURCE_URL to spring.datasource.url.

  • The test is whether the code could be open-sourced without leaking anything.
  • Secrets come from a secrets store, injected at run time.
  • Profiles are fine for defaults, but not as the place where production values live.

See it in the infographic: The twelve factors on a running service

What do stateless processes and disposability mean for a Spring Boot service in practice?

Stateless means no instance keeps anything another request needs: HTTP sessions go to Spring Session with Redis or become tokens, uploads go to object storage, and scheduled jobs use a lock such as ShedLock so only one replica runs them. Disposable means it starts in seconds and stops cleanly: server.shutdown=graceful stops new requests and finishes the open ones on SIGTERM, and consumers stop polling and commit before exit. Then the platform may kill any instance at any time.

  • Test it by killing instances during a load test.
  • Long-running work belongs in queues with retries, not in a request thread.
  • Startup time matters for scale-out and recovery, so keep the context lean.

See it in the infographic: The twelve factors on a running service

Is a well-built monolith on Kubernetes cloud native?

It can be. If it is built once, configured by the environment, stateless, starts fast, stops gracefully, logs to stdout and scales out with replicas, it follows the factors. Size is a separate question: microservices add independent deploys and scaling per part, and cost a distributed system. A modular monolith that follows the factors is often the better start.

Check yourself

1. A team builds orders-staging.jar and orders-prod.jar from the same commit, each with its own properties file inside. Which factor does it break?
Show answers
  • Config, and build, release, run: Correct. Config belongs in the environment, and one build should serve every release.
  • Logs: Incorrect. Nothing here concerns how logs are written.
  • Port binding: Incorrect. How the app exposes HTTP is unaffected.
2. A containerized service writes rolling log files to /var/log/orders. What does the twelve-factor approach say?
Show answers
  • Write the log to stdout and let the platform collect it: Correct. Logs are an event stream; storage and routing are the platform's job.
  • Mount a volume so the log files survive restarts: Incorrect. It keeps the files, but every instance's logs stay scattered and unmanaged.
  • Give the container a bigger disk: Incorrect. The files still vanish with the container and need rotation.