Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 1

Externalizing state and scaling a service to four instances

Build a small cart service that keeps sessions in memory, watch it break behind a round-robin proxy with four instances, move the state to PostgreSQL, prove the shared counter stays correct under concurrent updates, and restart the fleet without losing a session.

Contentsand lesson path

What you will learn

  • Make a stateful service horizontally scalable by externalizing session and cache state, and choose an autoscaling signal and limits.

01. Goal and setup

Lesson 01 said that cloning a service only works when any instance can serve any request. In this lab you see what that means. You will run a small cart service as one instance and then as four behind a round-robin proxy, and watch a guest's cart break as requests move between instances. Then you will move the state into a shared store, check that the count stays exactly right when 400 updates arrive at once, and replace the whole fleet without losing the cart.

You need Python 3.10 or later, Docker, and a bash shell on Linux or macOS (on Windows, use WSL 2). The lab was tested with Python 3.12.13, psycopg 3.3.9, psycopg-pool 3.3.3 and the postgres:17-alpine image. Everything listens on 127.0.0.1 only, on ports 18600 to 18604 and 18632.

Session data often lives in Redis or Valkey, which keep data in memory and can expire keys automatically. This lab uses PostgreSQL because it is one docker run away almost everywhere, and because the two lessons here, where state lives and how it is updated, hold for any shared store with atomic updates. In Redis the atomic step would be INCR; in PostgreSQL it is an UPDATE that adds one in the database.

Terminal: project folder and virtual environment
mkdir scale-lab && cd scale-lab
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -q --disable-pip-version-check "psycopg[binary,pool]"
python -c "import sys, psycopg, psycopg_pool; print(sys.version.split()[0],
  psycopg.__version__, psycopg_pool.__version__)"
Expected output (your version numbers may differ)
3.12.13 3.3.9 3.3.3

Create schema.sql, then start PostgreSQL and create the table. --tmpfs keeps the database files in memory, so nothing is left on disk, and --rm removes the container when it stops. The loop waits until the server accepts TCP connections, because the image runs a short set-up phase first.

SQL · schema.sql
CREATE TABLE carts (
  sid   text PRIMARY KEY,
  items integer NOT NULL DEFAULT 0 CHECK (items >= 0)
);
Terminal
docker run -d --rm --name scale-lab-pg -e POSTGRES_PASSWORD=lab \
  -p 127.0.0.1:18632:5432 --tmpfs /var/lib/postgresql/data postgres:17-alpine
until docker exec scale-lab-pg pg_isready -h 127.0.0.1 -U postgres -q; do
  sleep 1
done
docker exec -i scale-lab-pg psql -U postgres < schema.sql
Expected output (after the container ID that docker run prints)
CREATE TABLE

02. Step 1: Write the cart service

The service has three routes. POST /session creates a guest session and returns a random session ID. POST /cart/items adds one item to the cart of the session named in the X-Session header, and GET /cart returns the item count. A browser would carry the session ID in a cookie; a header keeps the lab readable. Every response says which instance answered.

The STORE variable picks where carts live. MemoryStore keeps a dictionary inside the process. PgStore keeps the same data in the shared carts table, through a pool of at most four connections per instance. UPDATE_MODE=naive switches the add operation to a read-then-write version, which you will need in step 6. The server is Python's built-in http.server, which keeps the lab free of frameworks; its documentation warns that it is not meant for production. Save this as app.py:

Python · app.py
"""Cart service for the scaling lab.

STORE=memory keeps carts inside this process; STORE=pg keeps them in PostgreSQL.
"""

import json
import os
import secrets
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

INSTANCE = os.environ.get('INSTANCE', 'i1')
PORT = int(os.environ.get('PORT', '18601'))
STORE = os.environ.get('STORE', 'memory')
UPDATE_MODE = os.environ.get('UPDATE_MODE', 'atomic')
DSN = os.environ.get(
    'DATABASE_URL', 'postgresql://postgres:[email protected]:18632/postgres'
)


class MemoryStore:
    """Session id -> number of items, held by this process only."""

    def __init__(self) -> None:
        self.carts: dict[str, int] = {}
        self.lock = threading.Lock()

    def create(self, sid: str) -> None:
        with self.lock:
            self.carts[sid] = 0

    def add(self, sid: str) -> int | None:
        with self.lock:
            if sid not in self.carts:
                return None
            self.carts[sid] += 1
            return self.carts[sid]

    def get(self, sid: str) -> int | None:
        with self.lock:
            return self.carts.get(sid)


class PgStore:
    """The same three operations, on a table that every instance shares."""

    def __init__(self, dsn: str) -> None:
        from psycopg_pool import ConnectionPool

        self.pool = ConnectionPool(dsn, min_size=1, max_size=4, timeout=5, open=True)

    def create(self, sid: str) -> None:
        with self.pool.connection() as conn:
            conn.execute('INSERT INTO carts (sid) VALUES (%s)', (sid,))

    def add(self, sid: str) -> int | None:
        with self.pool.connection() as conn:
            if UPDATE_MODE == 'naive':  # read the count, then write count + 1
                row = conn.execute(
                    'SELECT items FROM carts WHERE sid = %s', (sid,)
                ).fetchone()
                if row is None:
                    return None
                conn.execute(
                    'UPDATE carts SET items = %s WHERE sid = %s', (row[0] + 1, sid)
                )
                return row[0] + 1
            row = conn.execute(  # one statement: the database does the + 1
                'UPDATE carts SET items = items + 1 WHERE sid = %s RETURNING items',
                (sid,),
            ).fetchone()
            return row[0] if row else None

    def get(self, sid: str) -> int | None:
        with self.pool.connection() as conn:
            row = conn.execute(
                'SELECT items FROM carts WHERE sid = %s', (sid,)
            ).fetchone()
            return row[0] if row else None


store = PgStore(DSN) if STORE == 'pg' else MemoryStore()


class Handler(BaseHTTPRequestHandler):
    def reply(self, status: int, **body: object) -> None:
        data = json.dumps({'instance': INSTANCE, **body}).encode()
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def answer(self, items: int | None) -> None:
        if items is None:
            self.reply(401, error='unknown session')
        else:
            self.reply(200, items=items)

    def do_POST(self) -> None:
        if self.path == '/session':
            sid = secrets.token_urlsafe(16)
            store.create(sid)
            self.reply(201, session=sid)
        elif self.path == '/cart/items':
            self.answer(store.add(self.headers.get('X-Session', '')))
        else:
            self.reply(404, error='not found')

    def do_GET(self) -> None:
        if self.path == '/cart':
            self.answer(store.get(self.headers.get('X-Session', '')))
        else:
            self.reply(404, error='not found')

    def log_message(self, format: str, *args: object) -> None:
        pass  # one log line per request would flood fleet.log


if __name__ == '__main__':
    banner = f'{INSTANCE} on 127.0.0.1:{PORT} store={STORE} update={UPDATE_MODE}'
    print(banner, flush=True)
    ThreadingHTTPServer(('127.0.0.1', PORT), Handler).serve_forever()

Check that the file compiles:

Terminal
python -m py_compile app.py && echo app.py ok
Expected output
app.py ok

03. Step 2: Add the proxy and the fleet script

The proxy is a load balancer in its simplest form. It listens on port 18600 and sends each request to the next backend in turn (round robin), whether or not that backend is healthy. Real load balancers add health checks, retries and connection reuse; the Load balancing skill covers them. Save this as proxy.py:

Python · proxy.py
"""Round-robin reverse proxy: python proxy.py LISTEN_PORT BACKEND_PORT [...]"""

import itertools
import sys
import threading
from http.client import HTTPConnection, HTTPException
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

LISTEN, *BACKENDS = (int(arg) for arg in sys.argv[1:])
ring = itertools.cycle(BACKENDS)
ring_lock = threading.Lock()


class Proxy(BaseHTTPRequestHandler):
    def forward(self) -> None:
        with ring_lock:
            port = next(ring)  # strictly the next backend in turn
        length = int(self.headers.get('Content-Length') or 0)
        body = self.rfile.read(length) if length else None
        headers = {'X-Session': self.headers.get('X-Session', '')}
        try:
            conn = HTTPConnection('127.0.0.1', port, timeout=10)
            conn.request(self.command, self.path, body=body, headers=headers)
            resp = conn.getresponse()
            status, data = resp.status, resp.read()
            conn.close()
        except (OSError, HTTPException):
            status, data = 502, b'{"error": "backend %d unreachable"}' % port
        self.send_response(status)
        self.send_header('Content-Type', 'application/json')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    do_GET = do_POST = forward

    def log_message(self, format: str, *args: object) -> None:
        pass


if __name__ == '__main__':
    print(f'proxy on 127.0.0.1:{LISTEN} -> {BACKENDS}', flush=True)
    ThreadingHTTPServer(('127.0.0.1', LISTEN), Proxy).serve_forever()

fleet.sh starts N instances on ports 18601 upwards plus the proxy, writes their process IDs to fleet.pids, waits until every port answers, and sends all output to fleet.log. Save it as fleet.sh:

Bash · fleet.sh
#!/usr/bin/env bash
# ./fleet.sh start N   start N app instances (ports 18601...) and the proxy (18600)
# ./fleet.sh stop      stop every process this script started
# STORE and UPDATE_MODE pass through to every instance; logs go to fleet.log.
set -euo pipefail
cd "$(dirname "$0")"
if [ "$1" = stop ]; then
  if [ -f fleet.pids ]; then kill $(cat fleet.pids) 2>/dev/null || true; fi
  rm -f fleet.pids
  sleep 1
  echo 'fleet stopped'
  exit 0
fi
if [ -f fleet.pids ]; then echo 'a fleet is running: ./fleet.sh stop first'; exit 1; fi
ports=()
for i in $(seq 1 "$2"); do
  INSTANCE="i$i" PORT=$((18600 + i)) python app.py >> fleet.log 2>&1 &
  echo $! >> fleet.pids
  ports+=($((18600 + i)))
done
python proxy.py 18600 "${ports[@]}" >> fleet.log 2>&1 &
echo $! >> fleet.pids
for port in "${ports[@]}" 18600; do  # wait up to 30 s for each port to answer
  for _ in $(seq 150); do
    (echo > "/dev/tcp/127.0.0.1/$port") 2>/dev/null && continue 2
    sleep 0.2
  done
  echo "port $port is not answering: read fleet.log"; exit 1
done
for pid in $(cat fleet.pids); do
  kill -0 "$pid" 2>/dev/null || { echo 'a process died: read fleet.log'; exit 1; }
done
echo "instances on ${ports[*]}: store=${STORE:-memory} update=${UPDATE_MODE:-atomic}"
echo 'proxy on 127.0.0.1:18600'

Check both files and make the script executable:

Terminal
python -m py_compile proxy.py && bash -n fleet.sh && chmod +x fleet.sh \
  && echo proxy.py and fleet.sh ok
Expected output
proxy.py and fleet.sh ok

04. Step 3: Write the client and run one instance

The client only talks to the proxy, as real users only see the load balancer. walk creates a session, adds four items one at a time and reads the cart; resume does the same with the session saved in session.txt; load sends 400 adds to one new cart from eight threads at once, a correctness test. bench spreads adds over one cart per thread to measure throughput; you will use it in lesson 05. Save this as client.py:

Python · client.py
"""Lab client, talking only to the proxy on port 18600.

walk:   new session, four adds, then read the cart (one request at a time)
resume: the same walk, reusing the session saved by the last walk
load:   400 adds to ONE new cart from 8 threads at once (a correctness test)
bench [ADDS] [THREADS]: adds spread over one cart per thread (a throughput test)
"""

import json
import sys
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.error import HTTPError
from urllib.request import Request, urlopen

BASE = 'http://127.0.0.1:18600'
SAVED = Path('session.txt')


def call(method: str, path: str, sid: str = '') -> tuple[int, dict]:
    req = Request(BASE + path, method=method, headers={'X-Session': sid})
    try:
        with urlopen(req, timeout=10) as resp:
            return resp.status, json.load(resp)
    except HTTPError as err:
        return err.code, json.load(err)


def show(label: str, status: int, body: dict) -> None:
    value = body.get('items', body.get('error'))
    print(f'{label:<7} {status} from {body.get("instance", "proxy")}: {value}')


def new_session() -> tuple[str, str]:
    status, body = call('POST', '/session')
    if status != 201:
        sys.exit(f'no session ({status} {body}): read fleet.log')
    return body['session'], body['instance']


def walk(resume: bool) -> None:
    if resume:
        sid = SAVED.read_text()
        print('reusing the saved session')
    else:
        sid, where = new_session()
        print(f'session 201 from {where}: created')
        SAVED.write_text(sid)
    for n in range(1, 5):
        show(f'add {n}', *call('POST', '/cart/items', sid))
    show('cart', *call('GET', '/cart', sid))


def load(adds: int = 400) -> None:
    sid, _ = new_session()

    def add_one(_: int) -> tuple[int, dict]:
        return call('POST', '/cart/items', sid)

    with ThreadPoolExecutor(max_workers=8) as pool:
        results = list(pool.map(add_one, range(adds)))
    ok = sum(1 for status, _ in results if status == 200)
    served = Counter(body.get('instance', 'proxy') for _, body in results)
    print(f'adds sent: {adds}, answered 200: {ok}')
    print('served by:', ' '.join(f'{name}={n}' for name, n in sorted(served.items())))
    print(f'cart holds {call("GET", "/cart", sid)[1]["items"]} items (expected {adds})')


def bench(adds: int, threads: int) -> None:
    sids = [new_session()[0] for _ in range(threads)]
    per_thread = adds // threads

    def run(sid: str) -> int:
        statuses = [call('POST', '/cart/items', sid)[0] for _ in range(per_thread)]
        return statuses.count(200)

    start = time.perf_counter()
    with ThreadPoolExecutor(max_workers=threads) as pool:
        ok = sum(pool.map(run, sids))
    seconds = time.perf_counter() - start
    print(f'{threads} carts, {ok} adds answered 200 in {seconds:.2f} s')
    print(f'throughput: {ok / seconds:.0f} adds/s')


if __name__ == '__main__':
    mode = sys.argv[1] if len(sys.argv) > 1 else 'walk'
    if mode == 'load':
        load()
    elif mode == 'bench':
        numbers = [int(arg) for arg in sys.argv[2:4]]
        bench(*(numbers + [4000, 16][len(numbers):]))
    else:
        walk(resume=mode == 'resume')

Start one instance with in-memory state, walk through a cart, then stop the fleet:

Terminal
STORE=memory ./fleet.sh start 1
python client.py walk
./fleet.sh stop
Expected output
instances on 18601: store=memory update=atomic
proxy on 127.0.0.1:18600
session 201 from i1: created
add 1   200 from i1: 1
add 2   200 from i1: 2
add 3   200 from i1: 3
add 4   200 from i1: 4
cart    200 from i1: 4
fleet stopped

With one instance, in-memory state is perfectly correct: every request reaches the process that holds the dictionary.

05. Step 4: Scale to four instances and watch it break

Terminal
STORE=memory ./fleet.sh start 4
python client.py walk
./fleet.sh stop
Expected output
instances on 18601 18602 18603 18604: store=memory update=atomic
proxy on 127.0.0.1:18600
session 201 from i1: created
add 1   401 from i2: unknown session
add 2   401 from i3: unknown session
add 3   401 from i4: unknown session
add 4   200 from i1: 1
cart    401 from i2: unknown session
fleet stopped

The session was created in the memory of i1. The next three requests reached i2, i3 and i4, which have never heard of it, so they answer 401 unknown session. The fourth add returns to i1 and succeeds, but the cart holds 1 item, not 4. Nothing crashed and nothing was logged; the service is simply wrong, which is the dangerous kind of failure.

A sticky session, where the load balancer pins each user to one instance, hides this symptom but keeps the cause: when that instance is removed by a deploy, a crash or an autoscaler, its carts vanish. The Twelve-Factor App guidance is blunt about it: processes should be stateless and share nothing, data that must persist belongs in a backing service such as a database, and sticky sessions should not be relied on.

06. Step 5: Move the state to PostgreSQL

Terminal
STORE=pg ./fleet.sh start 4
python client.py walk
Expected output
instances on 18601 18602 18603 18604: store=pg update=atomic
proxy on 127.0.0.1:18600
session 201 from i1: created
add 1   200 from i2: 1
add 2   200 from i3: 2
add 3   200 from i4: 3
add 4   200 from i1: 4
cart    200 from i2: 4

Same code, proxy and request order, but now four instances served one cart and every answer is right. The instances have become interchangeable: none of them owns the cart. Leave this fleet running.

07. Step 6: Check correctness under concurrent updates

Sequential requests are the easy case. Now send 400 adds to one cart from eight threads at once, spread over all four instances:

Terminal
python client.py load
Expected output
adds sent: 400, answered 200: 400
served by: i1=100 i2=100 i3=100 i4=100
cart holds 400 items (expected 400)

Every add was counted once. Now restart the fleet in naive mode, where each instance reads the count, adds one in Python and writes the new value back:

Terminal
./fleet.sh stop
STORE=pg UPDATE_MODE=naive ./fleet.sh start 4
python client.py load
Illustrative output (your final count will differ, but stay well below 400)
fleet stopped
instances on 18601 18602 18603 18604: store=pg update=naive
proxy on 127.0.0.1:18600
adds sent: 400, answered 200: 400
served by: i1=100 i2=100 i3=100 i4=100
cart holds 210 items (expected 400)

All 400 requests succeeded, yet about half the items vanished. This is a lost update: two instances read the same count, say 57, both compute 58 and both write 58. PostgreSQL behaved correctly. Under its default isolation level, Read Committed, the second UPDATE waits for the first to commit, then writes its own value, computed from a stale read. The atomic version lets the database do the arithmetic, items = items + 1, and the documentation explains that the second updater then works on the updated row. Three naive runs on the test machine ended at 210, 220 and 226 items.

So moving state out of the instances is necessary but not sufficient: every update to shared state must be atomic in the store. Restore the correct mode:

Terminal
./fleet.sh stop
STORE=pg ./fleet.sh start 4
Expected output
fleet stopped
instances on 18601 18602 18603 18604: store=pg update=atomic
proxy on 127.0.0.1:18600

08. Step 7: Replace the whole fleet

Scaling in and deploying both remove instances. Stop all four, start two new processes, and continue the cart that you created in step 5:

Terminal
./fleet.sh stop
STORE=pg ./fleet.sh start 2
python client.py resume
Expected output
fleet stopped
instances on 18601 18602: store=pg update=atomic
proxy on 127.0.0.1:18600
reusing the saved session
add 1   200 from i1: 5
add 2   200 from i2: 6
add 3   200 from i1: 7
add 4   200 from i2: 8
cart    200 from i1: 8

The count continues from 4 to 8, although none of the processes that served the first four adds still exists. Instances can now come and go, which is what makes autoscaling and rolling deploys safe. The price is a network round trip to the store on every request, and a new dependency whose capacity you must plan (lesson 02 sized exactly this kind of connection pool).

Caches follow the same reasoning. A per-instance cache of read-mostly data, such as product descriptions, can stay in memory, because losing it costs only a reload. But each instance's copy goes stale on its own schedule, so two requests may see different prices until the entries expire, and a new instance starts with an empty cache. Data that every instance must agree on, such as rate-limit counters or values that must change everywhere at once, belongs in a shared cache or store.

Clean up when you are done:

Terminal
./fleet.sh stop
docker stop scale-lab-pg
deactivate

09. Check your understanding

Practice check · 3 questions

Shared state in the lab

Three questions about what you just ran.

Q1. In step 6 the load run printed `served by: i1=100 i2=100 i3=100 i4=100` and `cart holds 400 items`. Which reading of these two lines is right?
Q2. Four instances run in memory mode behind the round-robin proxy. A client creates a session (served by `i1`) and then sends eight adds, one at a time. How many adds return 200?
Q3. You are scaling a web tier out to many instances. Which of these is still reasonable to keep in each instance's own memory?
Practice only: not graded, not saved, not evidence.

10. Apply it

Extend the lab towards the skill's practice task:

  1. Sessions in a real store expire. Add an expires_at column, move it 30 minutes ahead on every request, and treat expired sessions as unknown. Decide who deletes old rows.
  2. Measure throughput with python client.py bench 4000 16 at one to six instances (./fleet.sh start 6 uses ports up to 18606). The numbers depend on your machine; lesson 05 shows how to fit them to a scalability model.
  3. If you have Redis or Valkey, write a third store class that uses INCR and compare it with the PostgreSQL version.

11. Review prompt

Without looking back: explain why the in-memory version worked with one instance and failed with four; what sticky sessions fix and what they leave broken; why the shared database alone was not enough in step 6; which per-instance caches are safe; and what new costs the shared store adds.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check