Backend Engineer Guide: Designing a Zero-Bloat Shared Core Package for Python Microservices
In a polyrepo or monorepo with 15 Python microservices, copying JWT middleware, structured JSON logging, OpenTelemetry trace propagation, and RFC 7807 error formatting across repositories quickly leads to configuration drift. Yet the opposite anti-pattern—a monolithic company-common library that pulls in Django, FastAPI, Celery, Boto3, and Pandas for every consumer—bloats container images by 600MB and creates circular dependency hell. As a backend engineer, I architect modular Python shared core packages using PEP 621 optional extras and strict zero-domain-coupling rules.
1. PEP 621 Optional Dependencies (Extras) in pyproject.toml
The base package must depend only on the Python standard library and lightweight typing primitives. Framework adapters (fastapi, django, celery) are exposed as isolated extras so a lightweight worker never installs web framework dependencies:
# pyproject.toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "afcom-platform-core"
version = "2.4.0"
description = "Zero-bloat observability, auth, and RFC 7807 error primitives"
requires-python = ">=3.11"
dependencies = [
"pydantic>=2.7,<3.0",
"PyJWT[crypto]>=2.8,<3.0",
]
[project.optional-dependencies]
fastapi = ["fastapi>=0.111.0", "starlette>=0.37.0"]
django = ["Django>=4.2"]
otel = ["opentelemetry-api>=1.25.0", "opentelemetry-sdk>=1.25.0"]
2. Propagating Correlation & Trace IDs via contextvars
By storing request correlation metadata in Python's native contextvars.ContextVar, both synchronous Django views and asynchronous FastAPI/httpx tasks automatically inject trace_id and tenant_id into every structured JSON log line and outbound HTTP header:
# afcom_core/telemetry_context.py
from contextvars import ContextVar
import json
import logging
import time
request_id_var: ContextVar[str] = ContextVar("request_id", default="unassigned")
tenant_id_var: ContextVar[str] = ContextVar("tenant_id", default="system")
class StructuredJsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
payload = {
"ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(record.created)),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
"request_id": request_id_var.get(),
"tenant_id": tenant_id_var.get(),
}
if record.exc_info:
payload["exc"] = self.formatException(record.exc_info)
return json.dumps(payload)