Cloud-Native Principles
Cloud-native as a set of runtime properties, not a stack of tools: the six pillars, leaning on the platform, design-first contracts, and the twelve-factor app reframed by who owns each factor.
Before any pattern, the principles that justify them. “Cloud-native” is not a list of products you adopt; it is a set of runtime properties a system has, and every later choice in this book either earns or spends one of them.
Six pillars
A cloud-native service exhibits six runtime properties, and the platform exists to make each of them the default:
Read each as a behaviour you design toward, not a product you install:
- Disposable: twelve-factor: fast start, clean stop, no local state, so the platform can move or restart it at will.
- Observable: it emits traces, metrics, and logs, and exposes health probes.
- Resilient: timeouts, retries, circuit breakers, graceful degradation.
- Elastic: it scales to load, and to zero.
- Automatable: declarative config, GitOps, self-healing.
- Loosely coupled: contracts not calls, async where it fits.
These six are the rubric for every pattern in this book. Hold each design decision up to them.
Lean on the platform
The most important move is to lean on the platform instead of reimplementing it. Don’t write your own retry library when the mesh does it at the wire; don’t build a bespoke autoscaler when KEDA scales on lag and request rate; don’t hand-roll metrics plumbing when OpenTelemetry and the LGTM stack give it to you. Every line of resilience code you write per service is a line you maintain forever and that drifts between teams. The platform makes the good behaviour the default; your job is to stay out of its way and use it.
Design-first: the contract precedes the code
Design-first is the cultural prerequisite for everything that follows. The
contract (OpenAPI, .proto, AsyncAPI) is agreed and registered before code
is written, owned by the producing domain, and gated in CI. Consumers code
against the contract and its generated stubs, never against your database. That
is what delivers independent deployability: the contract is the
service boundary. Skip it and you get distributed coupling: the worst of both
worlds.
The twelve-factor app, revisited
The twelve-factor app is the 2011 Heroku methodology that first codified what we now call cloud-native. It predates Kubernetes yet maps onto it almost perfectly. Here are all twelve, one line each.
The useful way to read it today is not to recite all twelve, but to split them by who owns each one: the few you still write, versus the many the platform now provides built in.
The left column is your job; the right column is the platform’s. The whole point of a cloud-native service is to do the left column well and trust the right column, which is exactly what this code does.
Twelve factors, mapped to our system
Grouped by what each factor asks of you, the twelve land on concrete choices in the running example, and most resolve to a platform default rather than code you write.
Five groups cover all twelve. Build & ship (codebase, dependencies, build/release/run, parity) becomes one repo and one image per release. Configure (config) is read from the environment. Run on the platform (stateless processes, concurrency, disposability, port binding) is the runtime’s job: KEDA scales it, Istio fronts it, the platform disposes of it. Attach resources (backing services) makes Postgres, Kafka, and the schema registry swappable URLs, never libraries compiled in. And operate (logs, admin processes) pushes telemetry and one-off tasks off the request hot path, into OpenTelemetry and Kubernetes Jobs. The section tags on each row point to where that group is treated in depth: most of the twelve are now adopted, not authored.
A twelve-factor service, ready for the platform
Two factors dominate the code you write: config from the environment (factor III) and health and readiness probes the platform calls. Here it is in each stack: pick your tab.
// application.yaml (excerpt), examples/01-cloud-native-principles/spring-boot
// config from env (factor III): SPRING_DATASOURCE_URL, SERVICE_VERSION -> service.version
//
// management.endpoint.health:
// probes.enabled: true
// group:
// liveness: // liveness: the process is up
// include: livenessState
// additional-path: "server:/healthz"
// readiness: // readiness: the pool answers a connection check
// include: readinessState,db
// additional-path: "server:/readyz" // DOWN -> 503, the pod leaves the Service
//
// spring-boot-starter-actuator serves both groups; no controller.
@RestController
public class OrderController {
private final OrderRepository orders; // Spring Data JPA over the shared orders table
private final String serviceVersion;
public OrderController(OrderRepository orders, @Value("${service.version}") String serviceVersion) {
this.orders = orders;
this.serviceVersion = serviceVersion;
}
@GetMapping("/orders")
public List<OrderResponse> listOrders() {
return orders.findAll(Sort.by("id")).stream().map(OrderResponse::of).toList();
}
}
# application.properties (excerpt), examples/01-cloud-native-principles/quarkus
# SmallRye Health: readiness includes the datasource check (503 when the database is down)
quarkus.smallrye-health.liveness-path=/healthz
quarkus.smallrye-health.readiness-path=/readyz
# db/init owns the schema: Hibernate only validates
quarkus.hibernate-orm.schema-management.strategy=validate
// Order.java: active record over the existing table
@Entity @Table(name = "orders")
public class Order extends PanacheEntityBase {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) public Integer id;
@Column(nullable = false) public String customer;
@Column(nullable = false, precision = 10, scale = 2) public BigDecimal total;
}
// OrderResource.java (excerpt)
@ConfigProperty(name = "service.version") String serviceVersion; // env, factor III
@POST @Path("orders") @Transactional
public OrderDto createOrder(@RestQuery String customer, @RestQuery BigDecimal total) {
var order = new Order(); order.customer = customer;
order.total = total.setScale(2, RoundingMode.HALF_UP);
order.persist(); // INSERT in the request transaction
return OrderDto.of(order); // the DTO, never the entity
}
// Program.cs (excerpt), examples/01-cloud-native-principles/dotnet
builder.Services.AddDbContext<OrdersContext>(o => o.UseNpgsql(connString)); // ConnectionStrings__Default (factor III)
builder.Services.AddHealthChecks()
.AddDbContextCheck<OrdersContext>("database", tags: ["ready"]); // readiness: the context can connect
var app = builder.Build();
app.MapHealthChecks("/healthz", new HealthCheckOptions // liveness: the process is up
{
Predicate = _ => false, // no dependency checks
ResponseWriter = (ctx, _) => ctx.Response.WriteAsJsonAsync(new { status = "ok" }),
});
app.MapHealthChecks("/readyz", new HealthCheckOptions // readiness: 200, or 503 out of rotation
{
Predicate = r => r.Tags.Contains("ready"),
ResponseWriter = (ctx, report) =>
{
var up = report.Status == HealthStatus.Healthy;
return ctx.Response.WriteAsJsonAsync(new
{
status = up ? "ready" : "down",
checks = new { database = up ? "ok" : "unreachable" },
});
},
});
# main.py (excerpt); pyproject.toml pins every direct dependency with ==, uv.lock the rest
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic_settings import BaseSettings
class Settings(BaseSettings): # config from env — factor III
database_url: str
kafka_bootstrap: str = ""
service_version: str = "0.0.0"
settings = Settings()
app = FastAPI(title="order-service", version=settings.service_version, lifespan=lifespan)
@app.get("/healthz") # liveness — the process is up
def healthz(): return {"status": "ok"}
@app.get("/readyz") # readiness — dependencies are reachable
async def readyz():
try:
async with pool.acquire() as conn:
await conn.fetchval("SELECT 1")
except Exception:
return JSONResponse({"status": "down", "checks": {"database": "unreachable"}}, 503)
return {"status": "ready", "checks": {"database": "ok"}}
// main.cpp (excerpt), examples/01-cloud-native-principles/cpp; conan.lock pins every library
using Callback = std::function<void(const HttpResponsePtr&)>;
const char* env(const char* name, const char* fallback) { // config from env, factor III
const char* v = std::getenv(name); return v ? v : fallback; // unset: the default
}
int main() {
g_version = env("SERVICE_VERSION", "1.0.0");
g_pool = std::make_unique<cndp::PgPool>(
env("PG_CONNINFO", "postgresql://appuser:apppass@postgres:5432/appdb"),
std::atoi(env("PG_POOL_SIZE", "4")));
app().registerHandler("/healthz", [](const HttpRequestPtr&, Callback&& cb) {
Json::Value j; j["status"] = "ok"; cb(HttpResponse::newHttpJsonResponse(j)); // liveness
}, {Get});
app().registerHandler("/readyz", [](const HttpRequestPtr&, Callback&& cb) {
const bool db_ok = db_ready(); // SELECT 1 via the libpq pool (retry elided)
Json::Value j; j["status"] = db_ok ? "ready" : "down";
auto resp = HttpResponse::newHttpJsonResponse(j);
if (!db_ok) resp->setStatusCode(k503ServiceUnavailable); // down: out of rotation
cb(resp);
}, {Get});
app().addListener("0.0.0.0", 8080).run(); // factor VII: port binding
}
// main.go (excerpt), examples/01-cloud-native-principles/go: config from env, two probes
func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(HealthResponse{Status: "ok"}) // liveness: the process is up
}
func (s *Server) handleReadyz(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
w.Header().Set("Content-Type", "application/json")
if err := s.pool.Ping(ctx); err != nil { // readiness: the database answers
w.WriteHeader(http.StatusServiceUnavailable) // 503: out of rotation, not restarted
json.NewEncoder(w).Encode(ReadinessResponse{Status: "down",
Checks: map[string]string{"database": "unreachable"}})
return
}
json.NewEncoder(w).Encode(ReadinessResponse{Status: "ready",
Checks: map[string]string{"database": "ok"}})
}
// main(): SERVICE_VERSION and DATABASE_URL come from the environment (factor III); the mux
// serves /, /healthz, /readyz and /orders on :8080 (factor VII, port binding)
How the code works
The same two ideas appear in every tab:
- Config comes from the environment, never from a baked-in file. Spring and
Quarkus resolve their datasource URL and
service.versionfrom environment variables, .NET readsConnectionStrings__Defaultthrough its configuration (env vars overrideappsettings.json), Python binds aBaseSettingsclass to env vars, and C++ and Go readstd::getenvandos.Getenv. One image, many environments: factor III, and the thing that lets the same artifact run in dev, staging, and production unchanged. - Two probes, not one. Liveness answers “is the process up?” If it fails,
the platform restarts the pod. Readiness answers “are my dependencies
reachable?” If it fails, the platform stops routing traffic to this instance
but leaves it running. Conflating the two is a classic mistake: a readiness
blip should drain traffic, not trigger a restart loop. The probe reads the
status code, not the body: Kubernetes counts any answer from 200 to 399 as
ready, so
/readyzanswers503(with"status": "down"in the body for people) when the database is unreachable. Every tab writes the two handlers by hand, as the examples do, so all six languages serve the same paths and bodies; Spring Boot Actuator, SmallRye Health and ASP.NET Core health checks are the framework routes to the same pair, and Kubernetes calls them the same way.
Notice what isn’t here: no retry logic, no scaling code, no port-binding plumbing. Those are the right column of Figure 1.3: the platform’s job.
Build, run, observe
cd examples/01-cloud-native-principles/python # or any of the six language stacks
docker compose up -d --build --wait
cd ..
./verify.sh
verify.sh runs the language-agnostic end-to-end checks against the running stack (13/13 in
each of the six languages), asserting the service reports its name, version and config
source from the environment (Factor III), liveness stays 200 while readiness flips from
200 to 503 and back as Postgres is stopped and restarted, and a CRUD round trip
(create an order, list it back) succeeds while the database is up.
With the service running, the probes are just HTTP. Hit liveness and readiness
with curl and confirm liveness returns healthy while the database is down but
readiness does not. That difference is the whole point. curl -i
localhost:8080/readyz should flip from 200 ready to 503 down as you stop the
database and back as you start it, without the process ever restarting.
The code is in examples/01-cloud-native-principles/. The run script there builds
and runs it; its README.md covers what it does and how to drive it.