Architecture
Four patterns that recur across the systems I build — shown as the request or event flow, alongside the code that implements the core decision.
Order events publish to Pub/Sub and are consumed asynchronously by a Cloud Run worker — decoupling order-taking from analytics so neither blocks the other.
1 func publishOrderEvent(ctx context.Context, t *pubsub.Topic, o Order) error {2 data, _ := json.Marshal(o)3 result := t.Publish(ctx, &pubsub.Message{Data: data})4 _, err := result.Get(ctx) // confirms publish, not processing5 return err6 }
Tenant identity resolves from JWT claims before a handler runs. PostgreSQL's search_path scopes every query to that tenant's schema — no per-query tenant_id checks required.
1 func TenantMiddleware(next http.Handler) http.Handler {2 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {3 claims := claimsFromContext(r.Context())4 ctx := withTenantSchema(r.Context(), claims.TenantSchema)5 next.ServeHTTP(w, r.WithContext(ctx))6 })7 }
An idempotency key is generated before the Daraja STK push. The webhook callback is signature-verified, then applied as an atomic upsert — retries and duplicates settle to one payment.
1 INSERT INTO payments (idempotency_key, order_id, status, amount)2 VALUES ($1, $2, 'completed', $3)3 ON CONFLICT (idempotency_key) DO NOTHING4 RETURNING id;5 -- no row returned => already processed, log and exit
Kitchen order updates publish to a branch-scoped Redis channel. A WebSocket layer subscribed to that channel fans the update out to every connected display in under 200ms.
1 func (h *Hub) HandleOrderEvent(branchID string, payload []byte) {2 channel := "branch:" + branchID + ":orders"3 h.redis.Publish(ctx, channel, payload)4 }56 // subscriber fans out to all websocket clients on this branch