Newsletter, guides

.env.development vs .env.production: Agent config

How .env, .env.development and .env.production differ, how Pydantic Settings loads them in order, and how to keep agent secrets out of git and laptops.

Asep Bagja PriandanaGuest authorSubscribe

, 8 min read, updated

Your agent has one .env file for every environment. It holds your real OpenAI key, your real Postgres URL, and DEBUG=True because you were testing yesterday. Someone on the team runs a load test against the local agent. It points at the production database, because local and production read the same file. Your LLM bill jumps and the vector store fills with test data.

.env.development and .env.production are per-environment config files that keep local and production settings apart by letting the loader pick one file from a single signal, such as APP_ENV. A base .env holds shared defaults. The mode file overrides it. Real environment variables override both. This guide covers the file layout, the load order in Pydantic Settings, and how production secrets should arrive.

Key takeaways

  • .env holds shared defaults, .env.development holds local values, and .env.production holds production values. One variable, such as APP_ENV, picks the mode file.
  • In Pydantic Settings, files in an env_file tuple load in order and each one overrides the last. Real environment variables always win over file values.
  • In production, inject secrets as environment variables from a secret manager. Do not ship a .env.production file with real keys to a server.
  • Commit only .env.example. Ignore every real env file with .env and .env.* in .gitignore, then re-include the example with !.env.example.
  • A secret that reached git history must be rotated. Rewriting history does not remove it from existing clones or forks.

Why does one .env file stop working once you have users?

Because one file name then means different things depending on who runs it. A single .env is fine for one engineer on one laptop. Add staging, a second engineer or a CI runner, and three failures show up:

  1. Debug settings reach production. Nobody flipped the flag, so tracebacks and prompts land in responses and logs.
  2. Local code writes to production data. A developer tests a tool and writes junk embeddings into the production vector store.
  3. CI spends real LLM credits. The test run inherited real keys because it read the same file.

None of these needs a careless engineer. They follow from a config model with one file for every environment.

What is the difference between .env, .env.development and .env.production?

.env is the base file loaded in every mode. .env.development and .env.production are mode files that override it. The loader reads APP_ENV, or NODE_ENV in JavaScript stacks, and loads .env first and the matching mode file second.

Frameworks use the same idea with small differences. Next.js checks process.env first, then .env.$(NODE_ENV).local, .env.local, .env.$(NODE_ENV) and finally .env. It skips .env.local when NODE_ENV is test. Python projects have no built-in convention, so you choose the order in your settings class.

Here is a layout that works for most agent services:

File Loaded when What it contains Committed to git?
.env every mode Shared defaults such as log level and timeouts, no secrets No
.env.development APP_ENV=development Scoped dev keys, local Postgres, DEBUG=true No
.env.test APP_ENV=test in CI Fake LLM provider, test database No
.env.production rarely a file Prefer injected environment variables No
.env.example never loaded Every key with a placeholder value Yes
Load order where field defaults are overridden by .env, then by the mode file chosen by APP_ENV, then by real environment variables

How do you load env files with Pydantic Settings?

Define one Settings class with pydantic-settings and list the files in env_file. Pydantic Settings moved out of Pydantic into its own package in Pydantic v2. It validates types, fails fast on missing keys, and lets real environment variables override file values.

# filename: app/config.py
# description: Single source of truth for agent configuration. Loads .env,
# then the file matching APP_ENV; real env vars override both.
import os
from functools import lru_cache

from pydantic import Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict

APP_ENV = os.getenv('APP_ENV', 'development')


class Settings(BaseSettings):
    app_env: str = APP_ENV
    debug: bool = False
    log_prompts: bool = False
    rate_limit_enabled: bool = True

    openai_api_key: SecretStr
    database_url: str
    vector_store_url: str

    log_level: str = 'INFO'
    request_timeout_s: int = Field(default=60, gt=0)

    model_config = SettingsConfigDict(
        env_file=('.env', f'.env.{APP_ENV}'),  # later file wins
        env_file_encoding='utf-8',
        extra='forbid',  # unknown keys in a dotenv file fail at startup
    )


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

Three details matter more than they look:

  • The env_file tuple loads in order, and each file overrides the previous one. So .env.development beats .env.
  • extra='forbid' is the default in Pydantic Settings. A typo in a dotenv file raises a ValidationError at startup instead of becoming a silent default. Keep it explicit so nobody switches it off by accident.
  • SecretStr hides the key in logs and reprs. Call get_secret_value() only where you build the client.

lru_cache on get_settings parses the files once per process, not once per request. In FastAPI, read it in the lifespan block or through Depends(get_settings). The Uvicorn and FastAPI production guide shows where those clients get created.

Why do debug flags belong in the same loader as secrets?

Because in an agent, debug flags change what leaks. They decide whether tracebacks reach HTTP responses, whether prompts land in logs, and whether the rate limiter runs. Those are security settings. They belong in the same typed loader as your API keys, with the same per-environment override.

Give each behavior its own flag instead of branching on the environment name. The Twelve-Factor App warns that grouping config into named environments does not scale. Each new deploy needs another name, and the combinations multiply.

# filename: app/agent.py
# description: Behavior comes from typed flags, not from checks on the
# environment name.
import logging

from app.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()


async def run_agent(message: str) -> str:
    if settings.log_prompts:
        # true only in .env.development and .env.test
        logger.debug('prompt: %s', message)

    if settings.rate_limit_enabled:
        await rate_limiter.check()

    return await llm.complete(message, timeout=settings.request_timeout_s)

app/agent.py never reads os.environ. It reads only settings. In pytest, build Settings(...) with explicit values and pass it in, with no patching of the environment.

How do you manage environment variables for an agent in production?

Inject them as real environment variables and keep files out of production. The file pattern is for laptops and CI. A production deploy works like this:

  1. The orchestrator, such as Kubernetes, ECS, Fly or Render, starts the container with APP_ENV=production.
  2. A secret manager injects OPENAI_API_KEY, DATABASE_URL and the rest as environment variables.
  3. Pydantic Settings reads those variables. They win over any file value, so a stray file cannot override them.

The same Settings class runs in every mode. Only the owner of the values changes. The Twelve-Factor test for this is simple: could you open source the code right now without leaking a credential?

Where config values come from in development, from .env files on the laptop, and in production, from a secret manager that injects environment variables

What should you .gitignore in an agent project?

Ignore every real env file and re-include only the example. Copy this excerpt:

# filename: .gitignore (excerpt)
# description: Ignore every real env file. Commit only .env.example.
.env
.env.*
!.env.example

# Other files that often hold the same secrets
.envrc
secrets.yaml
secrets.yml
config/local.json

The !.env.example line re-includes the example file. New contributors see every variable they need, with placeholders such as OPENAI_API_KEY=sk-replace-me. Check the rule with git check-ignore -v .env.development.

If a real .env already reached git, git rm does not erase it from history. GitHub’s guidance is to revoke or rotate the secret first. A history rewrite still leaves the data in other people’s clones and in forks. For where config meets the rest of a chatbot stack, see the production AI chatbot system design guide.

What to do next

  1. Rename your current .env to .env.development. Replace production keys in it with scoped dev keys.
  2. Move shared, non-secret defaults into .env. Create .env.example with every key and a placeholder, and commit only that file.
  3. Add the .gitignore excerpt and confirm it with git check-ignore -v.
  4. Replace every os.environ.get(...) with a Settings field. Use SecretStr for keys.
  5. Replace checks on the environment name with one flag per behavior, such as log_prompts and rate_limit_enabled.
  6. Set APP_ENV=production in your deploy and inject secrets from your secret manager. Never copy a .env file to a server.
  7. Add a pre-commit secret scanner such as gitleaks so a key is caught before it reaches the remote.

Frequently asked questions

What is the difference between .env and .env.development?

.env is the base file that loads in every mode, so it should hold shared defaults and no secrets. .env.development loads only when the app runs in development and overrides .env. It holds local values such as a dev API key and a local database URL. A variable like APP_ENV or NODE_ENV decides which mode file loads on top.

Should you commit .env files to git?

No. Commit only .env.example, which lists every required variable with a placeholder value. Put .env and .env.* in .gitignore and re-include the example with !.env.example. If a real secret reaches git history, rotate it first. Rewriting history does not remove the secret from clones or forks that already exist.

Which file wins when the same key is in .env and .env.development?

The mode file wins. In Pydantic Settings, files in the env_file tuple load in order and each one overrides the previous one. So with ('.env', '.env.development'), the development value is used. A real environment variable with the same name beats both files, which is how a secret manager overrides everything in production.

Do you need a .env.production file?

Usually not. In production, the platform or a secret manager should inject values as real environment variables. A .env.production file with real keys means production secrets sit on disk and can be copied around. If you keep one, store only non-secret production defaults in it and keep it out of git.

Is .env.development the same as .env.local?

No. In Next.js, .env.development holds defaults for development mode, while .env.local holds overrides for one machine. Next.js checks .env.local before .env.development and skips it during tests. Python projects have no built-in .env.local rule, so pick one convention per repo and list it in the README.

Sources

Build what you just read, with Param, live

  1. You read the guide

  2. Free Live LabBuild a Second Brain with Claude CodeA second brain over your notes, docs and Linear that answers with sources and serves the same memory to any agent over MCP.Free seat
  3. ProWatch the video coursesDesign a Software Factory for Your Coding Agents, Build Your First Software Factory Execution Harness and each new course as the sessions are cut. The first lesson of each is free after you sign in.$149 a year
  4. WorkshopAI Agents in Production for EngineersA multi-agent system deployed with an identity per agent, permissions, guardrails, an LLM gateway, traces and evals, plus a checklist for your own agents.$497
  5. BuildcampAgentic AI Buildcamp for Engineers & PMsDesign, build and deploy a production agentic AI system in four weeks$997

Subscribe to Top 1% Engineers

One issue at a time on building AI systems that hold up in production: architecture, the open source that matters, and what to do on Monday. Every number cited.

We email you each new issue. You can leave at any time. Privacy

More guides

See the newsletter and every guide