No server state
Why it matters Session stores are where scaling and restarts hurt: sticky sessions, a shared cache to run, carts lost on deploy. If the client can safely hold the state, the server has nothing to lose.
A small shop runs on a few short-lived serverless functions. Nothing is kept between requests, and two requests from the same shopper often hit different machines. The cart must still work. The only thing the functions share is a secret key.
HMAC: a signature made from a message and a secret key (hmac.new(key, message, "sha256")). Anyone can read the message; without the key, nobody can change it and produce a matching signature. Compare signatures with hmac.compare_digest.
import hmac, base64, json
body = json.dumps({"mug": 2}).encode()
sig = hmac.new(b"secret", body, "sha256").digest()
base64.urlsafe_b64encode(body) # cookie-safe textWrite make_token(cart, secret, now), read_token(token, secret, now) and add_item(token, sku, qty, secret, now). A cart is a dict of product code to quantity; secret is bytes; now is the time in whole seconds. add_item returns a new token with qty added.
Limits. No server state: the hidden tests read your tokens with a fresh copy of your code that shares no memory with the one that made them. read_token (and add_item) must raise ValueError for: any changed, added or removed character (unless the cart still reads back exactly the same), parts of two tokens joined together, a token made with a different secret, and a token more than 3,600 seconds old. A 50-item cart must fit in 4,000 characters, using only letters, digits and - _ . ~.
Spotted a problem in this lesson? Report it · Ask about this lesson
This exercise opens soon
Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.