skip to content

In pydantic-settings, what does each Settings() call cost, and how should a service load its settings once per process?

level: middleimportance: should knowfreq 50%

answer

  1. every call re-reads every source
  2. snapshot, not live view
  3. build at startup, reuse
  4. swap, don't reinitialise

basics

~10 s

Each Settings() call re-reads the environment, the .env file and secret files and revalidates every field, so a service builds one instance at startup, often behind functools.lru_cache, and reuses it.

solid answer

~40 s

Constructing a `BaseSettings` subclass runs every source again: it reads `os.environ`, opens and parses any configured `.env` file, looks up configured secret files and validates every field. Calling `Settings()` inside each request therefore repeats file I/O and validation, and two calls can even return different values if the environment changed in between. The usual pattern is to build the object once while the process starts, as a module-level instance or a function wrapped in `functools.lru_cache`, and pass that object around. That also means a bad value raises `ValidationError` at startup. An instance is a snapshot: changing `os.environ` later does not change it. To reload, build a new instance and swap the reference; calling `settings.__init__()` reloads in place but mutates an object other code may be reading.

code

python · 19 lines
python
from functools import lru_cache

from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env")

    debug: bool = False
    request_timeout_seconds: float = 5.0


@lru_cache
def get_settings() -> Settings:
    return Settings()


settings = get_settings()  # reads env and .env, validates, raises here if invalid
assert get_settings() is settings  # later calls reuse the same object

go deeper

for a junior

Remember that Settings() reads its sources once when built, and that services create one instance at startup and reuse it.

for a middle

Explain what each construction does, file reads and full validation, why per-request construction is wasteful, and how lru_cache and test overrides fit together.

for a senior

Design reload behaviour deliberately: build off the event loop, swap the reference atomically, and know which code still holds the old snapshot.

for a principal

Decide whether a service supports live reload at all; restart-on-change keeps one snapshot per process and is simpler to reason about than partial reloads across threads.

## What construction actually does A `BaseSettings` instance is not a live view of the environment. It is a **validated snapshot** taken when the object is constructed. Each `Settings()` call: 1. runs every configured **source** in priority order: initialiser arguments, environment variables, the `.env` file, the secrets directory, defaults; 2. **reads files** for the dotenv and secrets sources: it opens and parses the `.env` file, and looks up a file per field in each secrets directory; 3. **decodes** complex values from JSON and **validates** every field, including defaults, because `BaseSettings` sets `validate_default=True`; 4. returns a new object that never looks at its sources again. The documentation's own reloading example shows the snapshot behaviour: after `os.environ["foo"] = "bar"`, an existing instance still reports the old `foo` until it is rebuilt. ## Why calling it per request is a mistake - **Cost.** File reads and full validation on every request add latency for no benefit. - **Async blocking.** Settings are loaded synchronously. In an async service, building settings with dotenv or secret files inside a coroutine blocks the event loop while the files are read. The documentation suggests `await asyncio.to_thread(Settings)` when you must build or reload from async code. - **Inconsistency.** Two calls in one request can see different values if something changed the environment or a file in between. - **Late failure.** A misconfiguration surfaces on whichever request first constructs the object, not at deploy time. ## The once-per-process pattern Build the settings object **once, at startup**, and hand the same object to everything that needs it: ```python from functools import lru_cache from pydantic_settings import BaseSettings, SettingsConfigDict class Settings(BaseSettings): model_config = SettingsConfigDict(env_prefix="APP_", env_file=".env") debug: bool = False request_timeout_seconds: float = 5.0 @lru_cache def get_settings() -> Settings: return Settings() settings = get_settings() # reads, validates, raises here if invalid assert get_settings() is settings # later calls reuse the same object ``` - A **module-level instance** works too; the cached function is popular because the first call, not the import, does the reading, which startup code can trigger explicitly, and because tests can call `get_settings.cache_clear()`. - Calling it during startup turns configuration errors into **startup failures**: the process exits with a `ValidationError` naming the field before it accepts traffic. - **Tests** should construct their own instance with keyword arguments, which outrank the environment, plus `_env_file=None` to keep a developer's `.env` out of the run. How a web framework hands this object to request handlers is that framework's business; the pydantic-settings side ends at "one validated instance". ## Reloading without tearing Sometimes a long-running process must pick up new configuration. Two documented ways: | Approach | What happens | Risk | |---|---|---| | `settings.__init__()` | the same object re-runs all sources and is updated in place | readers can see a partially updated object mid-reload | | build a new `Settings()` and rebind the reference | a complete object replaces the old one | none from the rebind; old holders keep the old snapshot | The documentation recommends the second: rebinding a reference is atomic, so concurrent readers always see a fully initialised object. If you rely on in-place reloading, you need application-level locking around the reload and every read. With `lru_cache`, a reload means `cache_clear()` followed by a fresh call, and any code that kept a reference to the old object keeps reading old values until it asks again. ## Testing with a cached instance A cache that lives for the whole process also lives for the whole test run, which is the usual source of flaky settings tests: 1. a test that sets an environment variable and then calls `get_settings()` may receive an object cached by an earlier test; 2. calling `get_settings.cache_clear()` before and after such a test forces a fresh read; 3. better still, code under test can accept a `Settings` object as a parameter, so a test builds `Settings(debug=True, _env_file=None)` directly and never touches the cache or the real environment. ## Summary - one `Settings()` call means all sources read and every field validated; - the result is a snapshot, so later environment changes are invisible to it; - build it once at startup, reuse it, and reload by replacing rather than mutating.

  • How do you reload settings safely in a running async service?
    Build a fresh instance off the event loop with `await asyncio.to_thread(Settings)`, then rebind the shared reference to it. Construction reads files synchronously, so doing it on the loop blocks other coroutines, and rebinding is atomic, so readers see either the old complete object or the new one, never a half-updated one.
  • Why can calling settings.__init__() to reload be risky?
    It re-runs all sources and updates the existing object in place. While that runs, another thread or coroutine reading the same object may see some fields updated and others not. The documentation advises building a new instance and swapping the reference instead, or guarding both the reload and every read with locks.

Like printing a timetable before a trip: printing it takes effort, so you print once and carry the copy; if the schedule changes you print a new sheet and swap it, rather than correcting the old one while someone is reading it.

  • A settings instance re-reads os.environ whenever an attribute is accessed.
  • Creating Settings() inside every request is free because values are cached internally.
  • Calling settings.__init__() is the recommended way to reload in a concurrent service.
  • Settings loading is asynchronous, so building it in a coroutine never blocks the loop.