Lab15 (Spring Boot/K8S): Running Stateful Applications with Kubernetes StatefulSets

In this post, we’ll explore how Kubernetes StatefulSets give PostgreSQL a stable identity, storage of its own and an ordered start-up, and how a Spring Boot app finds it through a headless Service.


This series of stories shows how to use Kubernetes in the Spring ecosystem. We work with a Spring Boot API and Minikube to have a lightweight and fast development environment similar to production.

Every controller in this series so far — Deployment, DaemonSet, Job, CronJob — treats its pods as interchangeable. A Deployment doesn’t care which pod answers a request; it hands out a random name, a random IP, and replaces a dead pod with an entirely new one that shares nothing with the old one except a label. That’s exactly the right model for a stateless Spring Boot API. It’s the wrong model for PostgreSQL: a database pod has an identity (its data directory, its role in a topology) that can’t just be swapped for a fresh one with a random name and empty storage.

StatefulSet is the workload controller built for that difference. This lab runs PostgreSQL as a StatefulSet — with a stable, predictable pod name, its own dedicated storage attached through volumeClaimTemplates, and startup ordering — then points a Spring Boot service at it using the stable DNS name a headless Service provides, and proves the storage survives a pod being deleted and recreated. This builds directly on Lab6’s Persistent Volumes: everything Lab6 taught about PersistentVolumeClaim lifecycle still applies here — StatefulSet just automates creating one PVC per replica instead of you writing one by hand.

Concept Overview

What actually makes a workload “stateful”

Not “uses a database” — every service in this series has used a database somewhere. A workload needs StatefulSet specifically when its identity matters: when a replacement pod has to come back with the same name, the same storage, and (often) the same position in a startup order, rather than being any interchangeable copy. PostgreSQL qualifies because its data directory is meaningful and non-interchangeable between pods; a Spring Boot REST API connecting to it doesn’t qualify, which is exactly why this lab keeps the Spring Boot service as a plain Deployment and only the database becomes a StatefulSet. Don’t reach for StatefulSet by default — reach for it when a Deployment‘s “any pod is as good as any other” assumption is actually false for your workload.

Stable network identity: what the headless Service actually provides

A normal (ClusterIP) Service load-balances across whichever pods match its selector — you get one virtual IP, and which specific pod answers any given request is unspecified. A headless Service (clusterIP: None) does the opposite: it provides no load-balancing virtual IP at all, and instead lets DNS resolve directly to each backing pod. Paired with a StatefulSet, this is what produces predictable per-pod DNS names:

postgres-0.postgres-headless.default.svc.cluster.local
postgres-1.postgres-headless.default.svc.cluster.local
postgres-2.postgres-headless.default.svc.cluster.local

postgres-0 isn’t a label or a convention — it’s the actual pod name, deterministic because StatefulSet names pods <statefulset-name>-<ordinal>, starting at 0. Delete postgres-0 and the StatefulSet controller recreates a pod with that exact same name — not a new pod with a random suffix the way a ReplicaSet would. postgres-0.postgres-headless keeps resolving correctly across that deletion, which is the entire reason a Spring Boot app’s SPRING_DATASOURCE_URL can hardcode it as a connection target instead of needing service discovery logic to find “whichever pod is currently the database.”

Stable storage: volumeClaimTemplates

Lab6 covered creating a PersistentVolumeClaim by hand and referencing it from a Deployment‘s volumes block — one PVC, shared (in practice, usually by one pod at a time) across whatever pod the Deployment happens to be running. StatefulSet automates the same underlying PVC/PV mechanism, but per replica: volumeClaimTemplates is a template, and the controller creates one real PVC from it for each ordinal, named <template-name>-<statefulset-name>-<ordinal> (postgres-data-postgres-0 in this lab). Critically, that PVC’s lifecycle is independent of the pod’s. Delete postgres-0, and the pod goes away; the PVC postgres-data-postgres-0 does not. When the controller recreates the pod, it reattaches that exact same PVC — same data, same disk. Scaling a StatefulSet down doesn’t delete PVCs either (by default) — scaling back up reattaches the same storage the higher ordinals had before, which is a safety property, not a footgun, but one worth knowing about explicitly (see Common Pitfalls for the storage-growth implication).

Ordered deployment and termination

A Deployment starts all its replicas roughly in parallel. A StatefulSet, by default (podManagementPolicy: OrderedReady), starts postgres-0 first and waits for it to be Running and Ready before creating postgres-1, and so on — and reverses that order on scale-down, terminating the highest ordinal first. This matters for genuinely ordered systems (a primary that must exist before replicas can attach to it, a cluster-formation sequence that depends on a bootstrap node) far more than it matters for this lab’s single-replica default — but the behavior is worth seeing directly, which is exactly what the scaling exercise in Implementation Step 7 demonstrates.

What a multi-replica StatefulSet does not give you for free

This is the single most common misunderstanding about StatefulSet, worth stating before writing a line of YAML: scaling a plain PostgreSQL StatefulSet to 3 replicas does not create a 3-node replicated database. StatefulSet guarantees stable identity, stable storage, and ordered lifecycle — nothing about it replicates data between pods. Three replicas of this lab’s PostgreSQL StatefulSet are three entirely independent Postgres instances, each with its own empty data directory, that happen to share a pod-naming and storage pattern. Real Postgres high availability (streaming replication, automatic failover) needs additional machinery — Patroni, a Postgres Operator (Zalando, CloudNativePG) — layered on top. This lab runs a single Postgres replica for the “real” demo and scales to 3 only to observe the ordering and per-pod storage mechanics directly, never claiming replication that isn’t there.

What We’re Building

                    ┌──────────────────────────┐
statefulset-demo │ postgres-headless (Svc) │ clusterIP: None
(Deployment, 2x) │ clusterIP: None │
│ └────────────┬─────────────┘
│ JDBC to │
│ postgres-0.postgres- ▼
│ headless ┌───────────────────┐
└──────────────▶│ postgres-0 │
│ (StatefulSet) │
└────────┬──────────┘
│
┌────────▼───────────┐
│ PVC: postgres-data-│
│ postgres-0 │ 1Gi, ReadWriteOnce
└────────────────────┘

Scaling exercise only (not the primary demo):
kubectl scale statefulset postgres --replicas=3
→ postgres-1 created only after postgres-0 is Ready
→ postgres-2 created only after postgres-1 is Ready
→ each gets its OWN independent PVC — no data is shared or replicated

Database Modeling

Entities and relationship

A Device can have many Readings.
A Reading belongs to exactly one Device.
+----------------+
| device |
+----------------+
| id (PK) |
| name |
| location |
+----------------+
|
| 1:N
|
+----------------+
| reading |
+----------------+
| id (PK) |
| device_id (FK) |
| value |
| recorded_at |
+----------------+

Schema

drop table if exists reading;
drop table if exists device;

create table device
(
id bigserial primary key,
name varchar(100) not null,
location varchar(255),

constraint uq_device_name unique (name)
);

create table reading
(
id bigserial primary key,
device_id bigint not null references device (id) on delete cascade,
value double precision not null,
recorded_at timestamptz not null default now()
);

create index idx_reading_device_id on reading (device_id);
create index idx_reading_recorded_at on reading (recorded_at);

device_id is not null with on delete cascade — a reading can’t exist without a device, and deleting a device deliberately takes its historical readings with it rather than leaving orphaned rows with a dangling foreign key. idx_reading_device_id backs the “all readings for this device” query every GET /api/devices/{id}/readings call makes; without it, that becomes a sequential scan the moment the table has any real volume. idx_reading_recorded_at supports time-range queries (e.g., “readings from the last hour”) that a real device-telemetry API would need even though this lab’s endpoints don’t expose one yet.

Seed data

insert into device (name, location)
values ('sensor-rack-a1', 'datacenter-1/rack-a1'),
('sensor-rack-b3', 'datacenter-1/rack-b3');

insert into reading (device_id, value, recorded_at)
values (1, 21.4, now() - interval '10 minutes'),
(1, 21.6, now() - interval '5 minutes'),
(2, 19.8, now() - interval '5 minutes');

ORM mapping notes

Reading.device is @ManyToOne(fetch = FetchType.LAZY) — eager fetching here would mean every Reading load pulls its parent Device whether or not the caller needs it, which turns “give me the last 500 readings” into 500 extra queries or an unwanted join, depending on how carelessly it’s accessed. hibernate.ddl-auto is validate, not update: Hibernate checks the entity mappings match schema.sql (applied by PostgreSQL’s own /docker-entrypoint-initdb.d mechanism, not by Hibernate) at startup and fails fast on drift, rather than silently altering a running database’s schema — the same reasoning as Lab-series entities before it.

Implementation

Step 1 — Domain and repositories

package com.bootlabs.statefulsetdemo.domain;

import jakarta.persistence.*;

@Entity
@Table(name = "device")
public class Device {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String name;

@Column
private String location;

protected Device() {
}

public Device(String name, String location) {
this.name = name;
this.location = location;
}

public Long getId() { return id; }
public String getName() { return name; }
public String getLocation() { return location; }
}
package com.bootlabs.statefulsetdemo.domain;

import jakarta.persistence.*;

import java.time.Instant;

@Entity
@Table(name = "reading")
public class Reading {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "device_id", nullable = false)
private Device device;

@Column(nullable = false)
private double value;

@Column(name = "recorded_at", nullable = false)
private Instant recordedAt;

protected Reading() {
}

public Reading(Device device, double value) {
this.device = device;
this.value = value;
this.recordedAt = Instant.now();
}

public Long getId() { return id; }
public Device getDevice() { return device; }
public double getValue() { return value; }
public Instant getRecordedAt() { return recordedAt; }
}
package com.bootlabs.statefulsetdemo.repository;

import com.bootlabs.statefulsetdemo.domain.Reading;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ReadingRepository extends JpaRepository<Reading, Long> {
List<Reading> findByDeviceIdOrderByRecordedAtDesc(Long deviceId);
}

Step 2 — Service layer

package com.bootlabs.statefulsetdemo.service;

import com.bootlabs.statefulsetdemo.domain.Device;
import com.bootlabs.statefulsetdemo.dto.CreateDeviceRequest;
import com.bootlabs.statefulsetdemo.dto.DeviceResponse;
import com.bootlabs.statefulsetdemo.exception.DeviceNotFoundException;
import com.bootlabs.statefulsetdemo.repository.DeviceRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DeviceService {

private final DeviceRepository deviceRepository;

public DeviceService(DeviceRepository deviceRepository) {
this.deviceRepository = deviceRepository;
}

public DeviceResponse create(CreateDeviceRequest request) {
Device saved = deviceRepository.save(new Device(request.name(), request.location()));
return DeviceResponse.from(saved);
}

@Transactional(readOnly = true)
public List<DeviceResponse> findAll() {
return deviceRepository.findAll().stream().map(DeviceResponse::from).toList();
}

@Transactional(readOnly = true)
public Device getOrThrow(Long id) {
return deviceRepository.findById(id).orElseThrow(() -> new DeviceNotFoundException(id));
}
}

ReadingService.record reuses DeviceService.getOrThrow to confirm the device exists before recording a reading against it — the full source (including ReadingService, DeviceController, ReadingController, and GlobalExceptionHandler, which maps a duplicate device name to 409 via DataIntegrityViolationException) is in the demo repository.

spring:
application:
name: statefulset-demo
datasource:
url: ${SPRING_DATASOURCE_URL:jdbc:postgresql://localhost:5432/devicedb}
username: ${SPRING_DATASOURCE_USERNAME:devicedb_app}
password: ${SPRING_DATASOURCE_PASSWORD:devicedb_app}
jpa:
hibernate:
ddl-auto: validate
open-in-view: false

management:
endpoints:
web:
exposure:
include: health,info
endpoint:
health:
probes:
enabled: true
health:
livenessstate:
enabled: true
readinessstate:
enabled: true
group:
readiness:
include: readinessState,db

include: readinessState,db is doing real work here, in the same way earlier labs wired in a custom indicator: Spring Boot auto-configures a database health check the moment a DataSource is on the classpath, but — exactly like a custom HealthIndicator — it does not automatically join the Kubernetes readiness group. Without this line, a Spring Boot pod would report Ready even while its database connection pool is failing every request, which is precisely the wrong behavior when postgres-0 is mid-restart: the app pod should drop out of the Service’s endpoint list until the database is reachable again, not keep accepting traffic it can’t actually serve.

Step 4 — Dockerfile

FROM maven:3.9.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn -B dependency:go-offline
COPY src ./src
RUN mvn -B clean package -DskipTests

FROM eclipse-temurin:21-jre-alpine
RUN addgroup -S spring && adduser -S spring -G spring
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
USER spring:spring
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]

Step 5 — The PostgreSQL StatefulSet

# Headless Service — clusterIP: None means no cluster-VIP load balancing.
# Instead it gives each pod its own stable DNS record:
# postgres-0.postgres-headless.default.svc.cluster.local
apiVersion: v1
kind: Service
metadata:
name: postgres-headless
spec:
clusterIP: None
selector:
app: postgres
ports:
- port: 5432
targetPort: 5432
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres-headless
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:16-alpine
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
valueFrom:
secretKeyRef:
name: postgres-credentials
key: POSTGRES_DB
- name: POSTGRES_USER
valueFrom:
secretKeyRef:
name: postgres-credentials
key: POSTGRES_USER
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-credentials
key: POSTGRES_PASSWORD
- name: PGDATA
value: /var/lib/postgresql/data/pgdata
volumeMounts:
- name: postgres-data
mountPath: /var/lib/postgresql/data
- name: init-sql
mountPath: /docker-entrypoint-initdb.d
readOnly: true
resources:
requests:
cpu: "250m"
memory: "256Mi"
limits:
cpu: "500m"
memory: "512Mi"
readinessProbe:
exec:
command: ["pg_isready", "-U", "devicedb_app", "-d", "devicedb"]
initialDelaySeconds: 5
periodSeconds: 5
livenessProbe:
exec:
command: ["pg_isready", "-U", "devicedb_app", "-d", "devicedb"]
initialDelaySeconds: 15
periodSeconds: 10
volumes:
- name: init-sql
configMap:
name: postgres-init-sql
volumeClaimTemplates:
- metadata:
name: postgres-data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi

PGDATA is set to a subdirectory (/var/lib/postgresql/data/pgdata), not the volume’s mount root — the official Postgres image’s own documentation flags that some volume plugins create filesystem artifacts (like lost+found) directly at a mount point, which initdb can trip over if it’s told to initialize the mount root itself. A one-line env var avoids an otherwise confusing first-boot failure.

readinessProbe uses pg_isready, not a TCP or HTTP check — it’s the actual Postgres client tool built for exactly this, confirming the server is accepting connections rather than just confirming a port is open (a port can be open while Postgres is still recovering WAL on startup).

volumeClaimTemplates is the one field that makes this a StatefulSet demo rather than just “a Deployment with a probe.” Apply this manifest and Kubernetes creates a PVC named postgres-data-postgres-0 automatically — no separate PersistentVolumeClaim manifest to write by hand, unlike Lab6.

Step 6 — Initialization SQL as a ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-init-sql
data:
01-schema.sql: |
drop table if exists reading;
drop table if exists device;
create table device ( id bigserial primary key, name varchar(100) not null, location varchar(255),
constraint uq_device_name unique (name) );
create table reading ( id bigserial primary key, device_id bigint not null references device (id) on delete cascade,
value double precision not null, recorded_at timestamptz not null default now() );
create index idx_reading_device_id on reading (device_id);
create index idx_reading_recorded_at on reading (recorded_at);
02-data.sql: |
insert into device (name, location) values ('sensor-rack-a1', 'datacenter-1/rack-a1'), ('sensor-rack-b3', 'datacenter-1/rack-b3');
insert into reading (device_id, value, recorded_at) values
(1, 21.4, now() - interval '10 minutes'), (1, 21.6, now() - interval '5 minutes'), (2, 19.8, now() - interval '5 minutes');

The official postgres image runs every .sql/.sh file under /docker-entrypoint-initdb.d, in filename order, exactly once — the first time the container starts with an empty data directory. The 01-/02- prefixes aren’t cosmetic; they guarantee the schema exists before the seed data tries to insert into it. Re-running the StatefulSet (or restarting postgres-0) after the volume already has data does not re-run these scripts — this is the same “only runs against a truly empty database” behavior the ClamAV and rolling-updates labs’ Postgres containers rely on, applied here through a ConfigMap instead of a bind-mounted file since there’s no host filesystem inside the cluster to mount from.

Step 7 — The Spring Boot Deployment, pointed at postgres-0

apiVersion: apps/v1
kind: Deployment
metadata:
name: statefulset-demo
labels:
app: statefulset-demo
spec:
replicas: 2
selector:
matchLabels:
app: statefulset-demo
template:
metadata:
labels:
app: statefulset-demo
spec:
containers:
- name: statefulset-demo
image: statefulset-demo:1.0.0
imagePullPolicy: Never
ports:
- containerPort: 8080
env:
- name: SPRING_DATASOURCE_URL
value: jdbc:postgresql://postgres-0.postgres-headless:5432/devicedb
- name: SPRING_DATASOURCE_USERNAME
valueFrom:
secretKeyRef:
name: postgres-credentials
key: POSTGRES_USER
- name: SPRING_DATASOURCE_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-credentials
key: POSTGRES_PASSWORD
resources:
requests:
cpu: "150m"
memory: "384Mi"
limits:
cpu: "500m"
memory: "512Mi"
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
---
apiVersion: v1
kind: Service
metadata:
name: statefulset-demo-service
spec:
type: ClusterIP
selector:
app: statefulset-demo
ports:
- port: 80
targetPort: 8080

The Spring Boot API itself stays a plain Deployment with two interchangeable replicas — it has no identity of its own to preserve, which is exactly the distinction Concept Overview opened with. postgres-0.postgres-headless (short form; Kubernetes’ DNS search domains fill in the rest within the same namespace) is hardcoded directly as the connection target — no service-discovery client library, no lookup logic, just a name that keeps resolving correctly across whatever happens to postgres-0‘s pod.

Step 8 — Deploy, then prove storage survives a pod restart

minikube start --cpus=4 --memory=8192
eval $(minikube docker-env)
docker build -t statefulset-demo:1.0.0 ./statefulset-demo

kubectl apply -f k8s/postgres-secret.yaml
kubectl apply -f k8s/postgres-init-configmap.yaml
kubectl apply -f k8s/postgres-statefulset.yaml
kubectl rollout status statefulset/postgres

kubectl apply -f k8s/app-deployment.yaml
kubectl rollout status deployment/statefulset-demo
kubectl port-forward svc/statefulset-demo-service 8080:80 &
curl http://localhost:8080/api/devices
curl -X POST http://localhost:8080/api/devices \
-H "Content-Type: application/json" \
-d '{"name":"sensor-rack-c2","location":"dc-1/c2"}'

Now delete the database pod directly and watch it come back:

kubectl get pvc
kubectl delete pod postgres-0
kubectl wait --for=condition=ready pod/postgres-0 --timeout=90s
curl http://localhost:8080/api/devices
[{"id":1,"name":"sensor-rack-a1",...}, {"id":2,"name":"sensor-rack-b3",...}, {"id":3,"name":"sensor-rack-c2",...}]

sensor-rack-c2 — the row inserted before the pod was deleted — is still there. The new postgres-0 pod reattached the exact same postgres-data-postgres-0 PVC; nothing about its data was lost, and the Spring Boot app reconnected to the same stable DNS name without any configuration change.

Step 9 — The scaling exercise: ordering and independent storage, explicitly not replication

kubectl scale statefulset postgres --replicas=3
kubectl get pods -l app=postgres -w
postgres-0   1/1   Running
postgres-1 0/1 Pending
postgres-1 0/1 Running
postgres-1 1/1 Running
postgres-2 0/1 Pending
postgres-2 0/1 Running
postgres-2 1/1 Running

postgres-1 isn’t even created until postgres-0 reports Ready; postgres-2 waits on postgres-1 the same way — the OrderedReady policy from Concept Overview, directly observable.

kubectl get pvc

Three separate PVCs, three separate empty data directories — postgres-1 and postgres-2 are freshly initialized Postgres instances with none of postgres-0‘s data, because nothing in a plain StatefulSet replicates anything between them. Scale back down:

kubectl scale statefulset postgres --replicas=1
kubectl get pods -l app=postgres -w
postgres-2   1/1   Terminating
postgres-1 1/1 Terminating

postgres-2 terminates first, postgres-1 second — the reverse of creation order. Their PVCs, however, are not deleted:

kubectl get pvc

Scaling back up to 3 later would reattach postgres-1‘s and postgres-2‘s original storage rather than starting fresh — see Common Pitfalls for why leaving orphaned PVCs around indefinitely is a cost, not just a convenience.

Testing

@WebMvcTest slices for both controllers, following the same pattern as the rest of this series:

package com.bootlabs.statefulsetdemo.controller;

import com.bootlabs.statefulsetdemo.dto.DeviceResponse;
import com.bootlabs.statefulsetdemo.exception.DeviceNotFoundException;
import com.bootlabs.statefulsetdemo.service.DeviceService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@WebMvcTest(DeviceController.class)
class DeviceControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private DeviceService deviceService;

@Test
void returns404WhenDeviceMissing() throws Exception {
given(deviceService.getOrThrow(eq(99L))).willThrow(new DeviceNotFoundException(99L));

mockMvc.perform(get("/api/devices/99"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.error").value("DEVICE_NOT_FOUND"));
}

@Test
void rejectsBlankDeviceName() throws Exception {
mockMvc.perform(post("/api/devices")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\",\"location\":\"dc-1/a1\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.error").value("VALIDATION_ERROR"));
}
}

These slices verify request handling and validation, deliberately without a real Postgres — the StatefulSet’s behavior (identity, storage persistence, ordering) isn’t something a @WebMvcTest can exercise at all; it’s infrastructure behavior, verified the way Step 8 and Step 9 verify it: against a real cluster.

Edge cases worth adding beyond what’s shown here: a POST to /api/devices with a name that already exists (expect 409, not a raw stack trace), a reading recorded against a nonexistent device ID, and — at the infrastructure level — confirming kubectl delete pvc postgres-data-postgres-0 while the pod is still running is refused or requires explicit force, since a live pod holding a PVC is exactly the scenario storage-loss protections exist for.

Performance Considerations

A single-replica Postgres StatefulSet is a single point of failure, by design, in this lab. That’s an honest tradeoff for a tutorial, not a production recommendation — this lab’s whole point is to demonstrate StatefulSet mechanics clearly, not to ship a highly-available database. A production Postgres deployment needs either a managed database service or an operator (CloudNativePG, Zalando’s postgres-operator) that layers real streaming replication and automated failover on top of the same StatefulSet/PVC foundation this lab builds directly.

ReadWriteOnce access mode means exactly one node can mount each PVC at a time. That’s normally invisible with replicas: 1, but it directly explains why a plain multi-replica Postgres StatefulSet can’t share storage between pods even if you wanted it to — RWO volumes structurally can’t be attached to two pods on two different nodes simultaneously, which is one more concrete reason “just scale the replica count” cannot produce a replicated database on its own.

PVC storage requests don’t shrink, and orphaned PVCs from a scale-down keep consuming real disk. After Step 9’s scale-up-then-down exercise, postgres-data-postgres-1 and postgres-data-postgres-2 are still Bound, still holding 1Gi each, on a cluster that’s back down to one active Postgres pod. In a real environment, forgotten orphaned PVCs from a scaling experiment are a genuine, recurring source of unexplained storage cost — clean them up explicitly (kubectl delete pvc) once you’re certain the data in them isn’t needed.

pg_isready-based probes are cheap, but Postgres startup time under real data volume is not instant. This lab’s empty, freshly-seeded database becomes ready in a couple of seconds; a Postgres instance recovering a large WAL after an unclean shutdown can take meaningfully longer. initialDelaySeconds/periodSeconds tuned for a demo database will be too aggressive for one carrying real production data — size probe timing against your actual dataset, not a lab default.

Common Pitfalls

  • Assuming a multi-replica StatefulSet gives you database replication. It gives you multiple independent database instances with stable identities and independent storage — nothing more. Real HA needs an operator or managed service layered on top; conflating “I set replicas: 3” with “I have a replicated, fault-tolerant database” is the single most consequential misunderstanding this lab exists to correct.
  • Mounting a PVC at the exact root the volume plugin manages, instead of a subdirectory. Skipping PGDATA‘s subdirectory setting can surface a confusing initdb failure the first time the container starts against a volume whose top level already contains plugin-created artifacts — a one-line env var avoids the entire class of failure.
  • Forgetting that scaling down does not delete PVCs. This is a deliberate safety property (nobody wants a scale-down typo to silently destroy data), but it means storage cost accumulates silently across scaling experiments unless someone explicitly reclaims it. Audit kubectl get pvc after any scaling exercise, not just after a deliberate deletion.
  • Connecting a stateless Deployment to a StatefulSet’s ClusterIP-load-balanced Service instead of a specific pod’s stable DNS name. For a genuinely multi-replica, uncoordinated set of independent databases, a normal Service would load-balance connections across all of them essentially at random — silently spreading reads and writes across instances that don’t share data, corrupting the mental model of “one database” entirely. Point at the specific ordinal (postgres-0.<headless-svc>) when there’s exactly one authoritative instance to talk to.
  • Treating the readiness probe on the app pod as sufficient without also wiring the database health check into it. Without management.health.group.readiness.include: readinessState,db, a Spring Boot pod reports Ready regardless of whether its database connection actually works — traffic keeps arriving at a pod that can’t serve it, exactly during the window (a postgres-0 restart) when routing away matters most.
  • Not accounting for ReadWriteOnce‘s single-node-mount constraint when planning any topology beyond one active writer. It’s invisible until the moment it isn’t — a second pod on a second node trying to mount the same RWO PVC simply won’t schedule, and the resulting Pending pod with a vague scheduling event is a confusing first encounter with a well-documented volume access mode limitation.

Alternative Approaches

A bare StatefulSet is the right foundation when a workload’s requirement is genuinely “stable identity and storage,” and the wrong destination if the actual requirement is “a highly available database” — that requirement needs an operator or a managed service on top, not a higher replica count on its own.

Key Takeaways

  • StatefulSet exists for workloads whose pod identity — stable name, stable storage — actually matters; a Spring Boot API without that requirement stays a Deployment, exactly as this lab keeps it.
  • volumeClaimTemplates automates per-replica PVC creation (postgres-data-postgres-0, -1, -2, …), and each PVC’s lifecycle is independent of its pod’s — deleting a pod doesn’t delete its data, and scaling down doesn’t delete the PVC either.
  • Scaling a StatefulSet’s replica count changes how many independent, identity-stable pods exist — it does not, by itself, replicate data between them; real database HA needs an operator or managed service layered on top.

The complete source code is available on GitHub.

Support me through GitHub Sponsors.

Thank you for Reading !! See you in the next post.

References

Related Posts