Skip to content

Global Mutable State

How to recognise shared mutable state that any module can change, why it breaks tests and concurrency, and how to refactor it into explicit dependencies.

6 min readCode smellCoupling

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 beforeEach or setUp that 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);
}

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.

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.