Global mutable state is data that lives at module, class or process level and that any code can rewrite: a module-level dict, a public static field, an exported object, a singleton with setters. Every function that reads it now depends on whatever every other function last wrote. That dependency appears nowhere in a signature. The cost shows up late. A test passes alone and fails in the full suite. Two concurrent requests swap each other's settings. An admin endpoint changes a value and a nightly job silently picks it up. In an interview, spotting this smell shows you think about hidden coupling, ordering and concurrency, not just whether the code is tidy.
Signs
How to spot it in a review.
- A module exports a plain object or dict, and several files assign to its fields directly.
- A function writes a shared value as a side effect so that a later function can read it, for example setting the current currency or tenant before formatting.
- Tests need a
beforeEachorsetUpthat resets globals, or they fail when run in a different order. - A function's output changes even though its arguments did not, because something elsewhere changed a static field.
- Searching for who writes a value returns call sites across unrelated layers: cron jobs, HTTP handlers, CLI scripts.
- Concurrent requests or async handlers produce results that belong to another caller.
What it looks like
A typical case, in three languages.
// pricing.ts - Brightline Freight quote service
export const pricing = {
currency: "EUR",
fuelSurchargePct: 12,
customerDiscounts: new Map<string, number>(),
};
// Called by the hourly fuel-index cron job
export function refreshFuelSurcharge(pct: number): void {
pricing.fuelSurchargePct = pct;
}
// Called by the admin panel
export function grantDiscount(customerId: string, pct: number): void {
pricing.customerDiscounts.set(customerId, pct);
}
export function quoteShipment(customerId: string, weightKg: number, currency: string): number {
pricing.currency = currency; // so formatQuote knows what to print
const base = weightKg * 1.8;
const withFuel = base * (1 + pricing.fuelSurchargePct / 100);
const discount = pricing.customerDiscounts.get(customerId) ?? 0;
return Math.round(withFuel * (1 - discount / 100) * 100) / 100;
}
export function formatQuote(amount: number): string {
return `${amount.toFixed(2)} ${pricing.currency}`;
}
export interface QuoteRequest {
customerId: string;
weightKg: number;
currency: string;
}
export async function handleQuote(
req: QuoteRequest,
audit: (message: string) => Promise<void>,
): Promise<string> {
const amount = quoteShipment(req.customerId, req.weightKg, req.currency);
await audit(`quote issued for ${req.customerId}`);
return formatQuote(amount);
}# pricing.py - Brightline Freight quote service
from typing import Awaitable, Callable, TypedDict
pricing = {
"currency": "EUR",
"fuel_surcharge_pct": 12.0,
"customer_discounts": {},
}
# Called by the hourly fuel-index cron job
def refresh_fuel_surcharge(pct: float) -> None:
pricing["fuel_surcharge_pct"] = pct
# Called by the admin panel
def grant_discount(customer_id: str, pct: float) -> None:
pricing["customer_discounts"][customer_id] = pct
def quote_shipment(customer_id: str, weight_kg: float, currency: str) -> float:
pricing["currency"] = currency # so format_quote knows what to print
base = weight_kg * 1.8
with_fuel = base * (1 + pricing["fuel_surcharge_pct"] / 100)
discount = pricing["customer_discounts"].get(customer_id, 0)
return round(with_fuel * (1 - discount / 100), 2)
def format_quote(amount: float) -> str:
return f"{amount:.2f} {pricing['currency']}"
class QuoteRequest(TypedDict):
customer_id: str
weight_kg: float
currency: str
async def handle_quote(
req: QuoteRequest,
audit: Callable[[str], Awaitable[None]],
) -> str:
amount = quote_shipment(req["customer_id"], req["weight_kg"], req["currency"])
await audit(f"quote issued for {req['customer_id']}")
return format_quote(amount)<?php
// Pricing.php - Brightline Freight quote service
final class Pricing
{
public static string $currency = 'EUR';
public static float $fuelSurchargePct = 12.0;
/** @var array<string, float> */
public static array $customerDiscounts = [];
}
// Called by the hourly fuel-index cron job
function refreshFuelSurcharge(float $pct): void
{
Pricing::$fuelSurchargePct = $pct;
}
// Called by the admin panel
function grantDiscount(string $customerId, float $pct): void
{
Pricing::$customerDiscounts[$customerId] = $pct;
}
function quoteShipment(string $customerId, float $weightKg, string $currency): float
{
Pricing::$currency = $currency; // so formatQuote knows what to print
$base = $weightKg * 1.8;
$withFuel = $base * (1 + Pricing::$fuelSurchargePct / 100);
$discount = Pricing::$customerDiscounts[$customerId] ?? 0;
return round($withFuel * (1 - $discount / 100), 2);
}
function formatQuote(float $amount): string
{
return sprintf('%.2f %s', $amount, Pricing::$currency);
}
/**
* @param array{customerId: string, weightKg: float, currency: string} $req
* @param callable(string): void $audit
*/
function handleQuote(array $req, callable $audit): string
{
$amount = quoteShipment($req['customerId'], $req['weightKg'], $req['currency']);
$audit("quote issued for {$req['customerId']}");
return formatQuote($amount);
}quoteShipment writes the request currency into shared state so that formatQuote can read it later. In the async TS and Python versions, while one request awaits audit, a second request can overwrite currency, and the first customer receives a USD label on a EUR price. The same leak happens in long-running PHP workers and in any test suite that shares the process. The fuel surcharge and discounts are also invisible inputs: you cannot tell from the signature that the quote depends on the last cron run or admin click.
Why it happens
How code ends up like this.
- It hides inputs. A function that reads a global has parameters you cannot see, so callers and reviewers cannot reason about what affects the result.
- It couples unrelated code by write order. The cron job, the admin panel and the request handler all depend on each other through one object, with no contract between them.
- It breaks under concurrency. Interleaved async tasks, threads or worker processes that reuse memory can read values another caller wrote moments earlier.
- It makes tests order-dependent. One test's writes leak into the next, so you end up with reset hooks that must know every global in the system.
- It resists change. Supporting a second tenant or region with different rates means rewriting every reader, because the code assumes there is only one value.
Treatment
The refactorings that cure it, and when to choose each.
- Separate Query from Modifier: Split Reads from State Changes
A function computes a result and also writes shared state as a side effect, like
quoteShipmentsetting the currency. Split it so the calculation returns a value and changes nothing. - Change Function Declaration: Fix a Signature Without Breaking Callers
A function reads a global it should receive. Add the value, or the object holding it, as a parameter and pass it in from the caller, ideally from the composition root.
- Replace Primitive with Object: Give Rule-Bearing Values a Type
Data travels separately from the context it needs, like an amount and a currency stored in a global. Wrap them in a
Moneyvalue so formatting no longer needs outside state. - Extract Class: Split a Class That Does Two Jobs
Several functions mutate the same shared fields. Move the data into a class such as
PricingTablethat owns its state, exposes narrow methods, and is created and injected explicitly. - Introduce Parameter Object: Bundle Parameters That Travel Together
Removing globals leaves functions with long lists of rates and settings. Group them into one immutable
PricingSnapshotthat a request reads from start to finish. - Move Function: Put Behaviour Next to the Data It Uses
Writers of the global are scattered across layers. Move them next to the class that now owns the state so every mutation goes through one place.
Payoff
What you get once it's gone.
- Every input to a calculation is visible in its signature, so behaviour is predictable from the call site.
- Concurrent requests stop leaking values into each other.
- Tests construct their own state and run in any order without reset hooks.
- Supporting several tenants, regions or price lists becomes a matter of passing a different object.
- Mutations go through one owner, so you can log, validate or lock them in one place.
When to leave it
Sometimes it's not worth fixing.
- Constants and configuration loaded once at startup and never written again are not this smell; read-only globals carry far less risk.
- A process-wide cache or connection pool that is internally synchronised and only exposes safe operations is shared state by design, not an accident.
- In a short script or one-off CLI tool with a single thread of execution, threading state through every call can cost more than it saves.
Common questions
Short answers to the usual doubts.
Is a singleton the same thing as global mutable state?
A singleton with setters or mutable fields is global mutable state with a class name on it. A singleton that is immutable after construction, or that only wraps a thread-safe resource, is much less of a problem. The real issue is unrestricted writes plus hidden reads, not the pattern itself.
What about request-scoped context like AsyncLocalStorage or contextvars?
These fix the concurrency leak because each request sees its own value. They still hide inputs from function signatures, so testing and reasoning stay harder than with explicit parameters. Use them for cross-cutting data like trace IDs, not for business inputs like prices or discounts.
How do I remove a global that hundreds of files read?
Go incrementally. Wrap the global in a class with read methods, route all writes through that class, then convert readers one call path at a time to receive the instance as a parameter. Once the last direct reader is gone, delete the global and create the instance at startup.
How do I explain this smell in an interview?
Name the concrete failure: hidden inputs, order-dependent tests, and data leaking between concurrent requests. Then describe the fix as making dependencies explicit: return values instead of side effects, pass state as parameters, and give mutable data a single owner that is injected rather than imported.
Are environment variables global mutable state?
They are global and technically mutable. If you read them once at startup into an immutable config object and inject that, they behave like constants. Reading and writing them throughout the codebase at runtime brings back every problem of this smell.