Sign in with Google to keep private notes

SWE notes

I did this at the last possible second

to prepare for a lab with Marshall Wace

Once you can explain the architecture, identify a cache hit versus a miss, diagnose stale data, and understand what Caddy's reverse_proxy does, you've covered the useful introductory material.

Things To Know:

N+1 Problem

Prevent Lazy Loading (SQLAlchemy)

from sqlalchemy import select

from sqlalchemy.orm import raiseload

users = session.scalars(

    select(User).options(raiseload("*"))

).all()

for user in users:

    print(user.addresses)  # Raises an exception!
from sqlalchemy.orm import selectinload, raiseload

users = session.scalars(
    select(User).options(
        selectinload(User.addresses),
        raiseload("*")
    )
).all()

for user in users:
    print(user.addresses)  # Works!

in django: use assert.numQueries() to ensure number of queries matches what you expect

  • raiseload() — catch unwanted lazy loading.
  • selectinload() / joinedload() — fetch relationships eagerly.
  • Query logging / query-count tests — detect repeated SQL, including N+1 problems that lazy-loading guards miss.

The point is you want to do a batch read after getting the categories, rather than redundant trips to the database. lol.

users = session.query(User).all()  # 1 query

for user in users:
    print(user.addresses)          # Up to N more queries

Cache-Aside (with Redis)

What is Redis: In memory handler for some database (at disc) bullshit
What cache aside: when u implement a cache to a performance buff for some of the data, but if it breaks the app defaults to just using the original database. This is called the primary.

Data is loaded in as per use of recency. And a cache stampede can be prevented with...

When a popular key expires, every concurrent reader observes the miss at the same instant. Without coordination, all of them would query the primary and overwrite the cache redundantly — a cache stampede.

If there are readers and writers then theres a lock that a writer can hold to tell the readers to wait before they can check the cache for their beloved value

primary.update_field("p-001", "price_cents", "699")
cache.invalidate("p-001")

writes to primary invalidate the cache so you have to go back and load them later

Cache stampede: When a popular key expires, you need to make sure only one of them does the job of going to the primary and repopulating the database. Or that's going to lead to a bit of redundancy.

-- Acquire a short-lived lock with SET NX PX. Returns 1 on acquire, 0 otherwise.
if redis.call('SET', KEYS[1], ARGV[1], 'NX', 'PX', ARGV[2]) then
    return 1
end
return 0

#and you will only release when the one holding it is the one who releases it
if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('DEL', KEYS[1])
end
return 0

#register script
def _load_with_single_flight(
    self,
    entity_id: str,
    loader: Callable[[str], Optional[dict[str, str]]],
) -> Optional[dict[str, str]]:
    cache_key = self._cache_key(entity_id)
    lock_key = self._lock_key(entity_id)
    token = secrets.token_hex(8)

    acquired = self._acquire_lock(
        keys=[lock_key],
        args=[token, self.lock_ttl_ms],
    )

    if acquired:
        try:
            record = loader(entity_id)
            if record is None:
                return None
            pipe = self.redis.pipeline()
            pipe.delete(cache_key)
            pipe.hset(cache_key, mapping=record)
            pipe.expire(cache_key, self.ttl)
            pipe.execute()
            return record
        finally:
            self._release_lock(keys=[lock_key], args=[token])

    # Another caller is loading. Poll briefly for the cache to populate.
    with self._stats_lock:
        self._stampedes_suppressed += 1

    deadline = time.monotonic() + (self.lock_ttl_ms / 1000.0)
    while time.monotonic() < deadline:
        time.sleep(self.wait_poll_ms / 1000.0)
        cached = self.redis.hgetall(cache_key)
        if cached:
            return cached

    return loader(entity_id)

and this is the best pattern: lazily invalidate keys in cache. dont try to keep them in sync

def invalidate(self, entity_id: str) -> bool:
    return self.redis.delete(self._cache_key(entity_id)) == 1

field level updates will arbitrarily require the data is in cache. And this is good when you have something which you're frequently updating. For example, like, a stock price (which might cause repeated full reloads otherwise)

some design decisions:
TTL higher means less primary reads but more staleness. there are some cases where staleness is unacceptable and for that you explicitly go check
use invalidate framework dont sync. syncing leads to bugs. cache asides strength is assuming the cache is probably stale

sometimes inspect your cache:

redis-cli HGETALL cache:product:p-001

redis-cli TTL cache:product:p-001

make sure your ttl is longer than tail latency of the primary read to prevent redundant reading

Memcached

Memcached is an in-memory key-value store for small arbitrary data (strings, objects) from results of database calls, API calls, or page rendering.

Basically it allows you to load on memory more than you would need to load on your database.
memcache is basically a server that gives you access to a big giant LRU hashmap. It uses a server you can call. Yes its faster. Wow.

HTTP caching

Private HTTP caching

Cache-Control: Private
Use private to ensure no unintended leakage
Usually controlled by Cookie
Think browser cache

Shared HTTP caching

proxy vs managed

these are in the area between the client and the server.

Key Comparison

Attribute Proxied Cache (Forward Proxy) Managed Cache (Reverse Proxy / CDN)
Position Near the client / user's network Near the origin / cloud edge
Ownership Third party (ISP, IT department) You (the service developer)
Interaction Passive (standard Cache-Control response headers) Active (APIs, instant invalidations, custom headers like s-maxage, edge config)
Impact of HTTPS Mostly blind/bypassed today unless TLS interception is configured Terminates TLS; caches normally

HTTP caching

Validation

if-modified-since: server sends 304 to tell them all is good in the hood header if a cached HTTP request expires. then the TTL can be renewed.

ETAG is additional hashing that allows us to check if there were any differences from the version on their version or the version here locally. if they match then 304. if mismatch then it will send 200 and send the info over in the response.

no-cache forces validation every time (must revalidate + age-level = 0). usable for anything beyond HTTPS/1.1

no-cache allows storage but requires validation e.g. using a 304 no modification since, while no-store does not allow storing at all

Caddy

Caddy’s reverse proxy lets clients access your Python application through a public HTTPS address, while the application runs on an internal address such as localhost:8000.

Suppose your Flask app runs through Gunicorn on port 8000:

Browser requests https://example.com/users
                 ↓
Caddy receives the request on HTTPS port 443
                 ↓
Caddy forwards it to http://localhost:8000/users
                 ↓
Python processes it; Caddy passes the response back

This solves several practical problems:

Problem What Caddy does
Your Python service speaks HTTP, but users need HTTPS Handles TLS certificates and encryption
You have multiple applications on different internal ports Routes each domain or path to the appropriate application
You want one public entry point Allows application servers to listen only on internal interfaces
You have multiple instances of an application Can distribute requests between them

With this configuration:

example.com {
    reverse_proxy localhost:8000
}

Your Python application handles application logic; Caddy handles the public-facing connection and forwards requests. You can expose an application server directly, but then you need to handle those public-facing responsibilities elsewhere.

If you don't specify a port, Caddy defaults to 443 for HTTPS. In that case you will also need permission to bind to low ports. A couple ways to do this on Linux:

  • Run as root (e.g. sudo -E).
  • Or run sudo setcap cap_net_bind_service=+p $(which caddy) to give Caddy this specific capability (before v2.11.8, use =+ep). Caddy raises it only when binding a privileged port, so the binary still starts in environments that drop all capabilities.

Here's the most basic caddy reverse-proxy command that gives you HTTPS:

caddy reverse-proxy --to :9000

Then try it:

curl -v https://localhost

You can customize the hostname using the --from flag:

caddy reverse-proxy --from example.com --to :9000

If you don't have permission to bind to low ports, you can proxy from a higher port:

caddy reverse-proxy --from example.com:8443 --to :9000

Articles to read next