Categorias
Programming Technology

The Principle Is Not the Mechanism: ISP, DIP, and Language Structures in Practice

A small refactor made me think: how many times do we mix a principle with mechanisms? For example, Interface Segregation and Dependency Inversion are many times seen naturally in OOP, but they are principles and they survive a change of paradigm. TypeScript is this interesting case: it supports both OOP and functional styles in the same codebase, and both can preserve the I and D from SOLID. This article separates the principles from the mechanisms that carry them, maps how OOP and functional TypeScript preserve the same design responsibilities. And it proposes yet another comparison of things that look tied together, but are separate concepts in the language structures underneath: where structural typing and duck typing share a philosophy but diverge in practice.

Contents

  1. The in-memory repository that made the mapping visible
  2. Preserve the responsibilities, change the mechanisms
  3. Map responsibilities, not syntax
  4. Service factories, closures, and composition
  5. Structural typing: the conformance mechanism
  6. Testing: where duck typing walks back in
  7. Untangling the five concepts
  8. The language field guide
  9. A good way to use them
  10. The honest counterpoint
  11. Checklist
  12. Recap

Obs.: Check the Glossary at the end if you need clarification on concepts I am using in the article.

The in-memory repository that made the mapping visible

In a production TypeScript API I work on, the persistence design was still evolving while the Use Cases needed to move forward. We deliberately introduced an in-memory implementation of the domain contract:

// infrastructure/repository/in-memory.user.repository.ts
import { randomUUID } from 'node:crypto';
import type { NewUser, User, UserRepository } from '../../domain/user';

const usersByDocument = new Map<string, User>();

async function findByDocument(document: string): Promise<User | null> {
  return usersByDocument.get(document) ?? null;
}

async function create(data: NewUser): Promise<User> {
  const user: User = { id: randomUUID(), ...data, createdAt: new Date() };
  usersByDocument.set(data.document, user);
  return user;
}

export const inMemoryUserRepository: UserRepository = { findByDocument, create };

The services that depended on UserRepository received it as a parameter:

export async function register(
  input: RegisterInput,
  users: UserRepository,
): Promise<User> {
  const existing = await users.findByDocument(input.document);
  // ...
  return users.create(input);
}

At the call site, the temporary seam was explicit:

await register(input, inMemoryUserRepository);

That parameter was deliberate scaffolding. It allowed the Use Cases to progress against the contract while making the temporary in-memory choice visible wherever the service was called.

Later, the Postgres implementation of UserRepository became available. We began removing the extra repository parameter and moving toward an agreed convention: import the repository and use it inside the service. That convention itself would become part of the question.

import { postgresUserRepository } from '../infrastructure/repository/postgres.user.repository';

export async function register(input: RegisterInput): Promise<User> {
  const existing = await postgresUserRepository.findByDocument(input.document);
  // ...
  return postgresUserRepository.create(input);
}

That was the direction of the refactor, not the conclusion of the design. It removed the temporary parameter and restored consistency with the surrounding code, but it also moved the implementation choice directly into the service and removed the visible substitution boundary. In PHP, I knew exactly where each responsibility lived. In TypeScript, the functional style I was working in didn't use those mechanisms.

In the OOP style, each responsibility had an obvious home: a small interface supported Interface Segregation; constructor injection supported Dependency Inversion; a Service Container selected implementations and assembled the graph; tests supplied another implementation of the same interface. The direct-import style looked different enough to raise the real question:

Am I giving up Interface Segregation, Dependency Inversion, centralised composition, or isolated testing? Is functional TypeScript unsuitable for these principles, or am I looking for their OOP mechanisms instead of their functional equivalents? Should this service become a class, or can the functional style preserve the same design qualities from implementation through testing?

The refactor did not reveal a missing principle. It revealed a comparison worth making: for every responsibility that had an obvious home in the OOP style, what technique (and what language structure) gave it an equivalent home in the functional style?

That comparison turned out to be a useful exercise in itself. Not just which pattern to use, but what is a principle, what is a mechanism, and what is a language structure. Where each of those pieces actually plays its role. The rest of this article works through that distinction, one responsibility at a time.

Preserve the responsibilities, change the mechanisms

The comparison becomes clearer when the creation of one service is separated from the composition of the whole application:

Design responsibility Common OOP mechanism Functional TypeScript mechanism
Keep the consumer contract narrow A small, consumer-specific interface A small structural contract
Create one service instance Invoke a class constructor directly or through a dedicated factory Invoke a service factory such as makeRegistrationService(...)
Retain injected dependencies Private object fields The returned functions' lexical closures
Compose the application graph Invoke constructors/factories manually at the composition root, or use a Service Container Invoke service factories manually at the composition root, or use a Service Container
Expose the wired application The entry point receives or resolves a root service/application object The composition function returns an application facade with already-wired operations
Test a consumer in isolation Inject a fake/mock implementation through the constructor Pass a structural or duck-typed double to the service factory

This makes the factory equivalence explicit. makeRegistrationService(users) is doing two familiar jobs at once: its parameters are the functional counterpart of constructor injection, and invoking it is the functional counterpart of constructing the service through new or through a small OOP factory. The returned closure or object of functions is the service instance.

It also keeps composition, composition root, and Service Container distinct:

  • Composition is the activity of assembling the graph.
  • The composition root is the application location where that activity happens.
  • A Service Container is one optional mechanism for performing composition and resolution, often with lifecycle, scope, or discovery features. It can be used in either an OOP or functional application.
  • An explicit composition function is manual composition, not a complete replacement for every container capability.

The composed result is another role again. The application.register operation on the returned application facade is a ready-to-use entry point into the wired graph. It is not a Service Container because callers are not resolving arbitrary services by token, and it is not managing service lifecycles. If application code asks a container for dependencies directly, that moves toward the Service Locator pattern rather than dependency injection.

None of these mechanisms creates a design principle by itself. A large interface still violates ISP. A constructor or factory typed to a concrete class still violates DIP. A container or composition function can centralise poor dependencies as efficiently as good ones. The value comes from assigning each responsibility deliberately.

Import/export syntax is not part of the comparison; both styles use ordinary module boundaries. The meaningful question is where the concrete implementation is selected. In the opening refactor, the Use Case selects postgresUserRepository itself and hard-wires the detail. In the mapped design, the composition root selects it and the service factory receives only the UserRepository contract.

The discovery wasn't any of the individual concepts, they were all familiar. It was the mapping between coding styles. How do OOP and functional TypeScript use different techniques and language structures to preserve Interface Segregation and Dependency Inversion, from implementation through isolated testing? Asking that comparative question put contracts, constructors, factories, closures, composition, containers, facades, and test doubles in their respective roles. The concepts stayed the same; the mechanisms changed.

That comparison opened a second layer: what structure in the language makes each technique possible? Class constructors and object fields create and retain dependencies in the OOP route. First-class functions and lexical closures do the equivalent work in the functional route, while ordinary function application composes the graph. TypeScript's structural type system checks contracts without nominal declarations. JavaScript's dynamic dispatch allows duck-typed doubles at runtime, while TypeScript can check the same doubles structurally before tests run. The organizing chain is therefore not only principle → technique, but design responsibility → technique → enabling language structure.

Map responsibilities, not syntax

Dependency Inversion and dependency injection are related, but they are not the same thing:

  • Dependency Inversion (the D in SOLID) is a principle about direction: high-level policy must not depend on low-level detail; both depend on abstractions.
  • Dependency injection is a technique that serves it: bind a concrete dependency outside the code that consumes it.

The OOP version stores an injected dependency in an object:

class RegistrationService {
  constructor(private readonly users: UserRepository) {}

  async register(input: RegisterInput) {
    const existing = await this.users.findByDocument(input.document);
    // ...
  }
}

The functional version stores the same dependency in a closure:

function makeRegistrationService(users: UserRepository) {
  return {
    async register(input: RegisterInput) {
      const existing = await users.findByDocument(input.document);
      // ...
    },
  };
}

Both consumers depend on UserRepository, not on a database implementation. Both receive the concrete dependency from somewhere else. The difference is where the language stores the provided value: an object field in one case, a lexical environment in the other.

Composition completes the mapping:

// composition/application.ts
import { postgresUserRepository } from '../infrastructure/repository/postgres.user.repository';

function createRegistrationApplication(users: UserRepository) {
  const registration = makeRegistrationService(users);
  return { register: registration.register };
}

const application = createRegistrationApplication(postgresUserRepository);

await application.register(input);

The composition root chooses the Postgres implementation, injects it once, and receives an application facade. Calling application.register does not choose, construct, or locate a repository. In a container-based application, a Service Container may perform this composition at the root. Here the composition function performs it manually. Neither the composition function nor the returned facade is itself a Service Container.

This is also where Interface Segregation fits. UserRepository should describe only what the registration Use Case needs. Structural typing does not guarantee ISP (nothing prevents us from declaring a fat contract), but it removes much of the implementation cost of keeping contracts small. Any value with the required shape can satisfy the consumer's contract without joining an inheritance hierarchy or declaring implements. (More details about implements down in the article.)

Service factories, closures, and composition

Three elements do different work here: the service factory creates a service, its parameters are the injection boundary, and the returned functions' closures retain the injected dependencies.

At the service level, calling makeRegistrationService(users) supplies the contract-typed dependency and creates the service. Every returned function then closes over users. This is the direct functional counterpart of a constructor receiving a value, assigning it to a private field, and producing an object instance, without exposing the dependency to every service call.

At the application level, a composition function can invoke several service factories and build the graph. The next example generalises the earlier registration-only case into a composition function for the full application graph:

interface ApplicationDependencies {
  users: UserRepository;
  mailer: Mailer;
  clock: Clock;
}

function createApplication(dependencies: ApplicationDependencies) {
  const registration = makeRegistrationService(dependencies.users);
  const profile = makeProfileService(dependencies.users);
  const reminders = makeReminderService(dependencies.mailer, dependencies.clock);

  return {
    register: registration.register,
    getProfile: profile.get,
    sendReminders: reminders.send,
  };
}

Call createApplication(...) once at the composition root, and each returned service closes over only the slice of the graph it needs; collectively, those services expose the complete, already-wired application. Production passes database, mail, and system-clock implementations. Tests pass in-memory repositories, recording mailers, and fixed clocks. The consumers remain unchanged.

Closure-based composition can make a Service Container unnecessary for a simple, static graph, but it is not a full replacement for the abstraction. The composition function builds the graph and each returned closure retains its relevant part. Together they cover the container's core composition responsibility: construct the graph centrally, bind implementations to contracts, and expose ready-to-use services. A container may additionally provide autowiring, named bindings, scopes, lifecycle management, decorators, interception, or plugin discovery, and it remains available in functional code when those capabilities earn their cost. In TypeScript, autowiring still needs runtime anchors such as classes or explicit string/symbol tokens; erased structural interfaces cannot be resolved directly. Manual composition is sufficient when those capabilities are not needed.

The two routes can now be summarised without treating module syntax as part of the comparison:

  • OOP: segregated interface → constructor/factory → dependencies retained in object fields → manual or container-assisted composition → root application object
  • Functional TypeScript: structural contract → service factory → dependencies retained in closures → manual or container-assisted composition → application facade

The architecture is preserved because each responsibility still has an explicit home. What changes is the default mechanism: lexical scope replaces instance fields, service factories replace construction through new, structural conformance replaces nominal declarations, and explicit composition can replace container resolution when the graph does not need richer container capabilities.

Anton van Straaten's fictional Qc Na koan captures the first equivalence: "objects are a poor man's closures; closures are a poor man's objects." Both bundle behaviour with retained state. Here that state includes the in-memory repository's Map and, in each service closure, precisely the dependencies that service needs.

Structural typing: the conformance mechanism

Service factories and closures answer how one service is created and retains its injected dependencies; the composition root answers where the full graph is assembled. Structural typing answers a simpler question: how does the compiler know a value satisfies the contract its consumer expects? It's what makes the functional mapping safe, not just short.

In a structurally typed system, a value satisfies a type by having the right shape: the required members, with compatible types. Names and declarations are irrelevant. UserRepository defines one such shape:

interface UserRepository {
  findByDocument(document: string): Promise<User | null>;
  create(data: NewUser): Promise<User>;
}

Any value with those two methods, and compatible signatures, has that shape. So when the in-memory repository assigns its object literal to that type. Consider:

export const inMemoryUserRepository: UserRepository = { findByDocument, create };

That single line is the conformance check. It's compile-time, exhaustive, and free: if the object is missing a method, has one with an incompatible signature, or the contract later grows, this line stops compiling. No implements, no registration, no adapter class. And it generalises: any object literal, class instance, or factory result that has the shape is a UserRepository. The contract is decoupled from every implementation's ancestry, which is why an in-memory object literal and a Postgres-backed implementation can be substituted at the composition root without changing a consumer.

You can watch the check evaporate the moment it's done its job. The in-memory repository didn't need implements. A Postgres-backed class can still use it for clarity, but it's optional, and it disappears at runtime. The TypeScript source:

class PostgresUserRepository implements UserRepository {
  async findByDocument(document: string) { /* ... */ }
  async create(data: NewUser) { /* ... */ }
}

compiles to plain JavaScript with no trace of the contract:

class PostgresUserRepository {
  async findByDocument(document) { /* ... */ }
  async create(data) { /* ... */ }
}

The interface and implements annotation disappear because they are type-system constructs. The class remains because a class is also a runtime JavaScript construct. Conformance was proven once, before the program ran, and then discarded. It's also why a TypeScript DI container can't autowire by interface the way C# or PHP can: at runtime there's no UserRepository to resolve against, only classes and string/symbol tokens. The same erasure that keeps contracts lightweight is the reason reflection-based containers cannot autowire by interface and must use runtime classes or explicit tokens.

This is also where the I of SOLID becomes cheaper to practise. A small contract requires little implementation ceremony (no base class, no implements, no registration), so keeping interfaces role-specific adds less friction. In a nominal OOP language, each new segregated interface adds a declaration that its implementations must adopt; structural typing removes that declaration tax. It does not guarantee Interface Segregation, but it makes the principle easier to apply consistently.

The contrast that makes this concrete is a nominal language, PHP, the reference OOP case here:

final class PostgresUserRepository implements UserRepository { /* ... */ }

function register(UserRepository $users): void { /* ... */ }

Here conformance is declared. An object with exactly the right methods but no implements UserRepository is not a UserRepository: pass it to register() and PHP throws a TypeError. Same shape, wrong ancestry, rejected. This is one reason adapters and containers become more prominent in nominal ecosystems: conformance is explicitly declared, so wiring becomes a first-class activity with its own tooling.

One distinction worth stating now, because it drives the rest of the post: TypeScript is structural for interfaces, object types, and (mostly) classes, and it checks that conformance statically, before the program runs. "Checked statically" is easy to wave past, but it's the entire difference between structural typing and the thing it gets mistaken for. And the fastest place to feel that difference isn't in production at all. It's the moment you sit down to write a test.

And I am a Test-Driven Developer. Therefore...

Testing: where duck typing walks back in

The style survives contact with production easily enough. The seam is typed, the closure captures a contract-typed value. Where it gets interesting is the first time you write a test.

To test a service in isolation, you need a stand-in for its dependency, a repository that never touches a database. In JS/TS we've done this for years with an ad-hoc object: just the methods the test exercises, nothing more. And here the old instinct kicks in, reach for a loose double:

// duck-typed double: no contract in sight
const users = { findByDocument: async () => null } as any;

This works. The test runs, the service calls findByDocument, the call resolves. That's duck typing: the object is accepted because, at the moment of the call, it happens to have the method. Nothing checked its shape ahead of time; the as any explicitly threw the check away.

And it raises the question this whole post circles: is that the same thing as structural typing? It feels identical, both say "shape is enough, ancestry is irrelevant." But the difference is exactly the when. Type the same double against the contract instead:

// structurally-typed double: checked against the contract, now
const users: UserRepository = {
  findByDocument: async () => null,
  create: async (data) => ({ id: 'x', ...data, createdAt: new Date() }),
};

Now the compiler enforces the whole shape before the test runs. Forget create, or let the real UserRepository grow a method, and this double stops compiling; the test tells you it drifted. The as any version compiles happily and only fails later, at runtime, if that path is even exercised.

Same philosophy, opposite failure mode. The loose double (as any) is widely used and genuinely convenient, and it's quietly the reason so many of us assume duck typing and structural typing are one thing. They aren't: typing the double : UserRepository is the small discipline that keeps a test double in the structural camp, and it's worth doing. But the recommendation isn't the point here. The point is that the moment you write a mock is the moment the two concepts visibly separate, which is exactly what the next section pulls apart.

Untangling the five concepts

Five ideas have been doing distinct work so far. Placing them side by side makes the boundaries explicit:

Concept What it is What it is not
Dependency inversion / injection DIP: a principle about direction; depend on abstractions (the D in SOLID). DI: a technique serving it; bind concretions elsewhere A framework, a container, or anything inherently class-shaped
OOP constructs Classes, constructors, implements; one mechanism for DI and encapsulation The definition of DI, or a requirement for Interface Segregation or Dependency Inversion
Closures Functions capturing their environment; another mechanism for retained private state, injected dependencies, and explicit graph composition A Service Container abstraction by definition, or a hack until "real" OOP arrives
Structural typing Static conformance decided by shape; checked before the program runs A dynamic-language feature; permission to skip contracts
Duck typing Runtime conformance: "if it quacks"; discovered at the call site, or not at all A synonym for structural typing

Read down the "what it is not" column and the responsibilities separate cleanly. Dependency injection is not a framework: an explicit composition function can bind the graph as truly as a container. OOP constructs are not the definition of DI: they're one mechanism among several, the one that happens to dominate nominal ecosystems. Closures are not a hack or a container by definition: they are a language mechanism that can retain one dependency or the complete composed graph.

The two that cause the most trouble are the last ones: structural typing vs duck typing. They share a philosophy, behaviour over ancestry, shape over name, and in TypeScript they even look identical to write, which is why they get treated as one thing. They are not. The difference is when the shape is checked. Structural typing checks it at compile time, by a type checker, before the program runs; the failure is a red squiggle in your editor. Duck typing checks it at runtime, at the moment of the call, by the call itself; the failure is a thrown error, or worse, silence, if the missing method simply never gets reached on that path.

Which answers the question the testing section left open: if structural typing isn't what makes duck typing possible, what does? The enabler is dynamic dispatch, the language resolving x.quack() against whatever x actually is at call time, with no prior type commitment required. That's a property of the runtime, not of the type system, and it's independent of whether conformance is judged by shape or by declaration. The clean proof is Python: it has had duck typing forever, with no structural type system at all; typing.Protocol (PEP 544) later added static structural checking as an opt-in for external type checkers, and the duck-typed runtime underneath didn't change one bit. So duck typing and structural typing aren't two names for one idea, they're independent answers to two different questions, how? and when?, and a language can choose each answer separately.

The language field guide

Put the two questions on two axes, how conformance is decided (by shape, or by declaration) and when it's checked (statically at compile time, or at runtime), and every language lands in a cell:

Checked statically (compile time) Checked at runtime
By shape TypeScript, Go (structural typing) Python, JS, Ruby (duck typing)
By declaration C#, Java (nominal + static) PHP with type hints (nominal + runtime)

The cells people forget are the interesting ones.

  • TypeScript: shape, static, and loose. An ad-hoc object literal conforms on the spot, no named type required. The cheapest contracts of any mainstream language. TypeScript provides static structural checking over a dynamically typed JavaScript runtime, so once the types are erased, what's left is duck typing.
  • Go: shape, static, and not loose. Interfaces are satisfied implicitly (structural, a type never says implements), but conformance still needs methods declared on a named type; there are no ad-hoc conforming literals and no runtime "try the call and see." Interface satisfaction operates through named interface types rather than TypeScript-style ad-hoc object compatibility. This is the answer to "is there structural typing without any duck typing?". Go is it, and it isn't a compromise. The idiomatic Go move of defining tiny consumer-side interfaces is Interface Segregation and structural typing working together, straight out of the textbook.
  • Python / JS / Ruby: shape, runtime. Classic duck typing, enabled by dynamic dispatch. Python then bolts on optional static structural typing via typing.Protocol (PEP 544) for anyone running a type checker, without touching the duck-typed runtime, the cleanest demonstration that the two are separable.
  • PHP: declaration, runtime. Nominal, but enforced at call time. With type declarations, objects of classes that declare implements pass; a mismatch is a TypeError when the call happens, not a compile error (PHPStan/Psalm drag the check earlier, as a lint). Drop the declarations and PHP becomes dynamically typed: no type enforcement on parameters, method calls resolved at runtime, but objects are still class instances, not ad-hoc shapes. That double identity, nominal-when-typed, dynamic-when-not, plus autowiring by type declaration is the same story that made the containers from section 3 inevitable.
  • C# / Java: declaration, static. Nominal, checked at compile time. The full ceremony (declare the interface, implements it, register it, inject it) and perfectly capable of clean dependency-inverted designs; the container exists to amortise the wiring cost the nominal type system creates in the first place.

The grid shows these are independent axes, and real languages occupy all four cells. Go is structural and statically checked, but without TypeScript's ad-hoc object compatibility; TypeScript is structural-and-loose yet fully static; Python is duck-typed with an optional structural upgrade; PHP is nominal without being static, the quadrant people forget exists. "Structural" and "duck" are not synonyms, and "nominal" and "static" are not the same axis. Once the grid is visible, the testing question becomes precise: a TypeScript double can rely on JavaScript's runtime duck typing, or it can be checked structurally before the test runs. The object may look the same; the guarantee is different.

A good way to use them

None of this argues against classes, and none of it argues against containers. It argues for choosing the mechanism on purpose. A few defaults fall out of everything above:

  • Keep contracts in the domain, named in the domain's language. UserRepository belongs in domain/user.ts, not in the infrastructure that implements it; the consumer owns the interface, the implementation conforms to it. This is the Go consumer-defined-interface instinct and Interface Segregation in one move.
  • For simple functional services, a factory + closure is a natural default. The dependency is captured once and stays private. Keep parameter passing for genuinely local composition or deliberate scaffolding. Put the complete graph in an explicit composition root (createApplication or equivalent), invoke it once with production implementations, and retain the returned application facade as the wired root object. That is where implementation choices remain centralised and tests gain a single, typed substitution boundary.
  • Treat class-vs-closure as a mechanism choice, not a moral one. Pick by team convention and by whether you genuinely need identity or lifecycle semantics, not because one of them is "real" dependency injection. They both are.

It's worth naming the design principle underneath, because it's the reason the cheap option is also the good one. In Vlad Khononov's Balanced Coupling model, a shared contract is the weakest, most distance-tolerant form of coupling between two components, exactly what you want across a module boundary, where the two sides may change and ship independently. Structural typing makes that weakest level of coupling nearly free to express, so in TypeScript the best-balanced design and the least-ceremony design are the same design. The one discipline the model insists on: keep the wiring explicit and greppable, a named seam you can find, because Balanced Coupling's warning is against implicit coupling, and implicit coupling is also structural typing's failure mode. Which is the honest counterpoint.

The honest counterpoint

The price of making conformance free is that conformance becomes implicit. Anything with the right shape satisfies a contract, including things that match only by accident. A single-method contract like { execute(): void } is satisfied by half the objects in a codebase; the type checker will happily accept a wrong one that merely fits. The narrower and more generic the contract, the more coincidental matches it invites, so the defence is to keep contracts role-named and non-trivial (UserRepository, not Doer), so that matching the shape actually means matching the intent.

Implicitness costs tooling, too. Without implements, "find all implementations of this interface" is a weaker query than in a nominal language, and renaming a contract member doesn't announce, at the declaration site, everyone who just broke. You lean harder on the compiler and on find-references, and a little less on the class hierarchy telling you who's involved.

The mitigation turns out to be the same thing as the recommendation from the previous section: an explicit, greppable composition root. A deliberate conformance point, const impl: Contract = ..., typed against the contract, living in that known location, turns implicit shape-matching back into a visible, findable decision. It's also, not coincidentally, the same discipline that keeps a test double structural rather than duck-typed. The functional style doesn't remove the need to be deliberate about coupling; it relocates the deliberateness from the type declaration to the wiring, and rewards you for keeping that wiring in the open.

Checklist

A quick test for "am I doing DI properly in this style?", whether or not you reached for a class:

  • Does the consumer depend on a contract, not a concrete implementation? (Take the contract as a factory parameter and capture it.)
  • Is the binding external to the consumer, captured by a service factory and selected at the composition root, rather than constructed inline?
  • Is every implementation, including test doubles, typed against the contract (: UserRepository), so drift fails at compile time instead of at runtime?
  • Are contracts small and role-named, so structural matching signals intent rather than coincidence?
  • Is the complete dependency graph explicit and greppable in one composition root, rather than having consumers select concrete implementations throughout the application?
  • Did you pick class-vs-closure for a real reason (convention, lifecycle, identity), not out of habit or a belief that one is "real" DI?

Recap

The article started with a refactor that removed a temporary parameter and raised a question: was I giving up Interface Segregation and Dependency Inversion by moving from OOP to functional TypeScript, or was I looking for OOP mechanisms where functional equivalents existed?

The answer turned out to be a comparison worth making. For every responsibility that had an obvious home in OOP, there was a functional technique that gave it an equivalent home:

  • Interface Segregation lives in small, role-named contracts. Structural typing removes the declaration tax that keeps contracts fat in nominal ecosystems.
  • Dependency Inversion lives in depending on abstractions, not on concretions. A factory parameter captures a contract-typed dependency as cleanly as a constructor.
  • Dependency Injection lives in binding concretions outside the consumer. A service factory and closure retain injected state as truly as an object field.
  • Composition lives in a single root where implementations are selected and the graph is assembled. A composition function does this as truly as a Service Container.
  • Conformance lives in shape, not ancestry. Structural typing checks it statically, before the program runs. Duck typing discovers it at runtime, at the call site. Same philosophy, different when.
  • The language field guide put that distinction on two independent axes:
    • How conformance is decided: by shape or by declaration.
    • When it's checked: statically at compile time, or at runtime.
  • Real languages occupy all four cells:
    • Go is structural and statically checked, but without ad-hoc object compatibility.
    • TypeScript is structural and loose, yet fully static.
    • Python is duck-typed with an optional structural upgrade.
    • PHP is nominal without being static.
  • "Structural" and "duck" are not synonyms, and "nominal" and "static" are not the same axis.
  • The honest counterpoint: making conformance free makes it implicit. Anything with the right shape satisfies a contract, including things that match only by accident. The defence is role-named, non-trivial contracts and an explicit, greppable composition root. A deliberate conformance point, typed against the contract, turns implicit shape-matching back into a visible, findable decision.
  • The principles stayed the same. The mechanisms changed:
    • Classes, constructors, and implements are one set of mechanisms.
    • Closures, factories, and structural contracts are another.
  • Neither set is the definition of the principles they carry. Picking between them is a mechanism choice, not a moral one.
  • The one discipline that travels across both styles: keep the wiring explicit and greppable. A named seam you can find is the difference between deliberate coupling and accidental coupling, whether the seam is a constructor parameter or a factory argument.

Glossary

  • OOP — Object-Oriented Programming: a programming style that organises state and behaviour around objects. For comparison, this article uses a common class-based arrangement: interfaces, constructors, implementations, and a Service Container.
  • SOLID: a family of five design principles associated with maintainable and adaptable software. This article focuses only on its I and D.
  • ISP — Interface Segregation Principle: consumers should not be forced to depend on operations they do not use; prefer small, role-specific contracts.
  • DIP — Dependency Inversion Principle: high-level policy should not depend directly on low-level details; both should depend on abstractions, and details should depend on those abstractions.
  • DI — Dependency Injection: a technique for supplying dependencies from outside the consumer. DI can support DIP, but the two are not synonyms.
  • Closure: a function together with the lexical environment it retains, allowing injected values to remain available after the factory that received them has returned.
  • Service Container: a central assembler or registry that selects implementations and wires services, often with additional lifecycle or resolution features.
  • Composition root: the single application location where concrete implementations are selected and the dependency graph is assembled.
  • Seam: a place in code where behaviour can be varied without editing the code that uses it. Coined by Michael Feathers in Working Effectively with Legacy Code. In this article, the repository parameter is a seam: you swap implementations at the call site without touching the service.

Further reading and references

Glossary concepts

Language and design mechanics

Categorias
Programming Segurança

Permissions and Authorisation: Implementing with Cedar

Disclaimer: This is the point-in-time version of my "Playbook - Permissions and Authorisation: Cedar Implementation", which I will keep up-to-date. This article is the sequel to "Permissions and Authorisation: A Practical Playbook", which covers the domain model, enforcement boundaries, and mechanism selection. Read that first. This article assumes the model is built and a policy engine is warranted.

The previous article ended with a guidance: introduce a policy engine when the model combines roles with ownership, relationships, tenant containment, and attributes; when the same decision must be made in several services; or when policy review, simulation, traceability, or controlled change is a real requirement. Cedar is one concrete option when that point is reached. This article walks through how to apply the playbook's model using Cedar specifically and where Cedar stops being the answer.

What Cedar is

Cedar is a policy language and decision engine developed by AWS and released open-source under Apache 2.0. It evaluates an authorisation request with four parts, being principal, action, resource, context (called PARC), plus a set of entities representing trusted domain facts and their relationships. It returns Allow or Deny and decision diagnostics.

Cedar's evaluation semantics provide three useful safety properties:

  1. Default deny. No matching permit means Deny. There is no implicit allow.
  2. Forbid wins. A matching forbid overrides any matching permit. Guardrails are expressible as first-class policy, not afterthoughts.
  3. Errors skip the affected policy. A policy evaluation error causes that policy to be skipped and reported in diagnostics rather than automatically determining the entire decision. The request continues to be evaluated against remaining policies.

The third rule makes validation and diagnostics operationally important. A faulty policy does not itself cause a global outage, but it can be skipped while another permit still allows a request that the faulty policy was meant to restrict. Validate policies against the schema before publication, alert on evaluation diagnostics, and test both policy and schema changes.

A Cedar design normally contains:

  • a schema for entity types, attributes, memberships, actions, and context shapes;
  • entities representing trusted domain facts and relationships;
  • permit and forbid policies;
  • a policy store and change process;
  • an application adapter that constructs the PARC request and relevant entity slice, invokes Cedar, records the decision, and enforces it.

What Cedar does not solve

Cedar is a decision engine, not a complete authorisation system. This is pivotal to understand what is not Cedar's responsibility. It does not:

  • authenticate users or issue/validate JWTs;
  • decide which entity data is true: your application must assemble trusted, correctly scoped entity data;
  • filter a database query automatically or protect a storage bucket on its own;
  • replace validation of input, tenancy checks, audit retention, rate limits, or business invariants;
  • provide a complete UI, approval workflow, or governance process for users editing policies.

If policy authors are customers or non-engineering staff, design policy administration as a product: constrained templates, preview/simulation, approval and rollback, audit history, and strict meta-permissions for who may grant which access.

When Cedar is a good fit

Cedar is particularly strong when a system needs combinations of RBAC, ownership/relationship rules, tenant containment, and attributes; when decisions are shared across services; or when policy review and explainability matter.

Use groups to represent broad roles and policies to grant role capabilities. Add resource relationships or attributes for rules that roles cannot express cleanly. Keep individual grants and exceptions narrow, scoped to both principal and resource where possible. Prefer fine-grained permissions in the model, then aggregate them into user-facing product roles or screens.

Cedar is not the only policy engine, and it is not always the right one. If your rules are few, stable, and local to one service, centrally tested application code is simpler and clearer. If you need a full relationship-based access control system with deep graph traversal, consider whether Cedar's entity model is expressive enough for your relationship depth or whether a dedicated ReBAC system is more appropriate. Choose based on the behaviour the system needs, not the novelty of the tool.

Implementing Cedar: a step-by-step approach

1. Start with one high-value boundary

Choose one coherent domain, such as organisation membership, documents, or projects, not the entire legacy permission surface. Keep existing authorisation in place elsewhere. Define the success measure: for example, all document operations are evaluated at one server-side boundary and the decision can be explained from logs.

This mirrors the playbook's general guidance: centralise decisions early enough that the model can evolve deliberately, rather than attempting a big-bang migration of every permission surface at once.

2. Define the Cedar schema and action vocabulary first

Define the namespace, entity types, action groups, and action applicability before drafting many policies. Ensure each action identifies the permitted principal and resource types and the specific transient context shape it accepts.

namespace ExampleApp {
  entity User in [Role, Organisation] {};
  entity Role {};
  entity Organisation {};
  entity Document in [Organisation] = { owner: User, locked: Bool };

  action "document.read" appliesTo {
    principal: [User],
    resource: [Document],
    context: {}
  };

  action "document.update" appliesTo {
    principal: [User],
    resource: [Document],
    context: {}
  };
}

This is illustrative only. The schema must reflect the actual domain and its authoritative data sources. The Cedar schema defines what an authorisation request and its entities are allowed to look like; it does not establish where those facts come from or whether they are trustworthy. That is the responsibility of the adapter and the data contract described in step 5. The action vocabulary is where the playbook's guidance on business actions applies directly: use document.read, document.update, invoice.approve — not HTTP verbs or UI labels. Make the resource explicit even for create and list operations, where the resource is normally the destination container or tenant.

3. Model policy rules as business rules

Policies should be specific and readable. A role grant and an owner rule may coexist; a forbid can express a guardrail that must win even if a role policy permits access.

// Role-based: document readers can read any document in their scope.
// Assumes the user's role membership is represented in the entity graph.
permit (
  principal in ExampleApp::Role::"document_reader",
  action == ExampleApp::Action::"document.read",
  resource
);

// Ownership-based: owners can update their own unlocked documents
permit (
  principal,
  action == ExampleApp::Action::"document.update",
  resource
)
when { resource.owner == principal && !resource.locked };

// Guardrail: locked documents cannot be updated, even by the owner
forbid (
  principal,
  action == ExampleApp::Action::"document.update",
  resource
)
when { resource.locked };

Do not paste this example into production unchanged. In particular, scope policies as tightly as the domain requires and validate all policy text against the deployed schema.

The forbid-wins semantics are what make Cedar's guardrails trustworthy. A locked-document rule expressed as forbid will override any permit including future permits you haven't written yet. This is qualitatively different from expressing the same constraint as a negative condition inside every permit, which silently stops applying when a new permit forgets to include it.

4. Create one authorisation adapter

Application code should call a small, well-tested boundary with a request such as:

authorize({ principal, action, resource, context }) → allow/deny + decision metadata

The adapter:

  • resolves canonical IDs (opaque, immutable — not display names or email addresses);
  • loads the minimum authoritative entity slice (principal, resource, and the relationships the policies might traverse);
  • calls the Cedar authorizer;
  • handles diagnostics according to the service's safety requirements;
  • emits safe audit telemetry (request/correlation ID, principal/resource type and opaque IDs, action, decision, applicable rule identifiers and version, evaluation errors, latency);
  • blocks execution on denial.

The adapter should not accept arbitrary Cedar entities or policy text from an untrusted caller. Entity data comes from trusted application sources; policy text comes from a versioned, reviewed policy store. Never from the request.

This is the same enforcement boundary the playbook describes, now with a concrete implementation: the adapter is where route additions cannot silently bypass the decision, because every protected operation passes through it.

5. Assemble the entity slice carefully

Cedar evaluates policies against the entities you provide, not against your database. The adapter must load the minimum authoritative entity slice: the principal, the resource, and the relationships the policies might traverse (group memberships, tenant containment, ownership links).

This is where the playbook's data contract guidance becomes concrete. For each entity attribute and relationship:

  • What is the canonical source?
  • What is the freshness expectation?
  • Who owns the data?

Keep principal, action, and resource facts in their respective models. Use request context only for transient, action-specific facts such as an MFA assertion, request time, or an IP/network signal not as a duplicate source for identity, role, tenant, or resource ownership. If the entity slice is wrong, the decision is wrong, regardless of how correct the policies are.

For “may Alice read Document X?”, the adapter might supply:

Fact Cedar input Authoritative source
Who is making the request? User::"alice", including role and tenant Identity and membership service
What is being accessed? Document::"x", including owner, classification, and locked state Document service/database
How are they related? Alice's group memberships; the document's folder and tenant Membership and document data
What is true only for this request? Verified MFA assertion, request time, client network Validated session/token and request infrastructure

The policies determine which of those facts are needed. A rule that permits Group::"editors" needs Alice's group membership; a rule that permits only the document owner needs its current owner; a forbid for locked documents needs the current locked state. The adapter assembles and validates this input; the client does not.

Why "carefully": three failure modes, all silent.

  1. Missing relationships. A policy says principal in Group::"editors". If you don't load Alice's group memberships, Cedar can't match the policy. It evaluates as if Alice is in no groups. The decision is Deny even though Alice is an editor. The policy is correct; the data slice is wrong.
  2. Stale data. Alice was removed from the editors group 5 minutes ago, but your entity slice was cached from 10 minutes ago. Cedar allows a request that should be denied. The freshness question above is about this.
  3. Wrong source. You put Alice's role in the request context (which the caller controls) instead of loading it from your identity store. A malicious or buggy caller passes role: admin in the context and Cedar grants admin access. The guidance above is warning against exactly this: context is for transient facts (MFA, IP, time), not for identity, role, or ownership, because those must come from trusted sources.

The "minimum" part: you don't load your entire user database into every authorisation call. You load the slice that the policies might traverse for this request. Too little → wrong decisions. Too much → latency and unnecessary data exposure. The "carefully" is about getting that boundary right.

6. Handle diagnostics as a first-class concern

Because evaluation errors are skipped rather than fatal, diagnostics are not optional telemetry, but safety signal. A policy that errors is a policy that is not applying. If that policy was a forbid guardrail, the request may be allowed by a different permit that the forbid was meant to override.

Handle diagnostics according to the service's safety requirements:

  • Alert on evaluation errors at a rate that indicates a policy or entity-slice problem, not a transient blip.
  • Treat a diagnostics-only decision (no matching permit or forbid, but errors present) as Deny unless the service has a deliberate, documented reason to do otherwise.
  • Include diagnostic information in audit records so post-incident investigation can reconstruct why a decision was made.

Cedar-specific verification

In addition to the general test strategy from the playbook, Cedar introduces its own verification surface:

Layer Verify
Schema validation Schema compiles, entity types and actions are consistent, context shapes match action definitions
Policy unit tests Each permit and forbid produces the expected decision for representative entity slices
Entity-slice mapping tests The adapter loads the correct entities and relationships for a given request. No missing relationships, no stale data
Diagnostics-handling tests Evaluation errors are surfaced, alerted, and do not silently allow access
Schema-change tests Adding, removing, or changing entity attributes or actions does not silently alter existing decisions

For every new policy, include at least one must allow, must deny, and must not leak scenario. Test actions, not UI controls, because direct API calls and background execution bypass the UI. This is the same discipline as the general playbook, now applied to Cedar's permit/forbid semantics.

Operational checklist for Cedar

Before implementation

  • One high-value boundary chosen, with existing authorisation preserved elsewhere.
  • Cedar schema reflects the actual domain: entity types, attributes, memberships, actions, and context shapes.
  • Action vocabulary uses business actions, not HTTP verbs.
  • Entity data sources identified: canonical source, freshness, and ownership for each attribute and relationship.
  • Adapter design defined: ID resolution, entity-slice loading, Cedar invocation, diagnostics handling, audit telemetry, and enforcement.

Before rollout

  • Policies validate against the schema in CI.
  • Policy changes have review, audit, and rollback paths.
  • The adapter is the sole entry point for Cedar evaluation — no bypass paths.
  • Entity-slice loading is tested for correctness and minimal scope.
  • Diagnostics are alerted on, not just logged.
  • Existing data/query/storage controls still enforce tenant and ownership boundaries.
  • Negative and regression tests prove denial causes neither disclosure nor side effect.

After rollout

  • Inspect allow/deny rates, diagnostics, latency, and unexpected denials.
  • Confirm no route or job bypasses the adapter.
  • Review forbid guardrails, stale entity data, and policy-store changes on a defined cadence.
  • Record incidents and confusing access requests as new regression cases or schema improvements.

Cedar-specific anti-patterns

In addition to the general anti-patterns from the playbook:

  • Trusting unvalidated entity data: passing request-supplied attributes or relationships into Cedar without resolving them from a trusted source. Cedar evaluates what you give it — incorrect entity data can produce incorrect authorisation decisions.
  • Forgetting forbid when adding new permits: a new permit that broadens access may override a constraint that was previously enforced by the absence of a permit, not by an explicit forbid. Express guardrails as forbid so they survive new permits.
  • Ignoring diagnostics: treating evaluation errors as harmless noise. A skipped forbid is a silent security gap.
  • Overloading context with entity facts: using the context map to pass principal roles, tenant membership, or resource ownership instead of modelling them as entities and relationships. Context is for transient, action-specific facts.
  • Policy-store drift: changing policies without schema validation, version pinning, or regression tests. A policy that validated against the previous schema may error against the new one.
  • Entity-slice gaps: loading the principal and resource but forgetting the relationships the policies traverse (group memberships, tenant containment). A policy that depends on principal in Role::"admin" will deny if the Role entity is not in the slice — silently and without a clear error.

References

Categorias
Programming Technology

Permissions and Authorisation: A Practical Playbook

Disclaimer: This is the point-in-time version of my "Playbook - Permission and Authorisation", which I will keep up-to-date.

Authorisation is a domain capability, not a collection of scattered endpoint conditionals. For every protected operation, decide consistently whether a verified principal may perform a business action on a specific resource in a defined context—and enforce that decision server-side before data or side effects are exposed.

Choose the simplest mechanism that preserves one consistent, server-side decision model. A few stable rules may be clearer as centrally tested application code; a policy engine becomes valuable when rules are expressive, auditable, shared across services, or need to evolve independently of individual endpoints.

To definitions:

Permission is a grant or entitlement.

Authorisation is the request-time decision and server-side enforcement that applies those grants to a principal, action, resource, and context.

When this matters

This becomes important when a system has any of the following:

  • users with more than one role or organisation;
  • tenant, ownership, project, folder, account, or team boundaries;
  • permissions that depend on resource state, relationships, time, location, MFA, or other trusted context;
  • customer-configurable or delegated access;
  • several services or endpoints that must make the same access decision;
  • audit, compliance, support, or incident needs that require explaining why access was allowed or denied.

A small internal tool with a stable administrator/member distinction may need only a simple, centrally tested server-side check. Do not introduce a policy engine merely to avoid a short, clear rule.

The mental model

Keep authentication and authorisation distinct

  • Authentication: who is making this request? Verify identity and session/token integrity.
  • Authorisation: may that verified identity perform this action on this resource now?
  • Entitlements / relationships: which roles, tenants, ownership relations, subscriptions, and delegations are true?
  • Enforcement: where is the decision applied before sensitive data or side effects occur?

An authenticated user is not automatically authorised. Client-side checks improve the user experience but never replace server-side authorisation. A role label alone is not a complete permission model.

Separate permissions from business rules

Permission answers whether a principal may perform an action on a resource:

Can Alice approve invoice #123?

Business rules answer whether that action is valid in the resource's current state:

Can an approved invoice still be edited?

These are different questions. An authorised user can still fail business validation, and a valid workflow transition can still be forbidden for that user. Workflow state may be a deliberate authorisation input, but permissions must not become a substitute for state-transition validation or domain invariants.

Ask the same question everywhere

Express every authorisation decision as:

Can principal P perform action A on resource R in context C?

Use business actions such as invoice.approve, project.member.invite, or document.download, rather than HTTP verbs or UI labels. Make the resource explicit even for create and list operations, where the resource is normally the destination container or tenant.

Design for default deny and least privilege

Start with no access. Add narrow, reviewable grants only where a business rule justifies them. Keep explicit prohibitions for non-negotiable guardrails, such as suspended accounts, cross-tenant access, or actions requiring MFA.

Every server-side path that reads protected data, changes state, invokes a privileged integration, or produces a sensitive export needs an enforcement point. Database row-level security, query predicates, and storage access controls remain necessary defence-in-depth; an application authorisation decision does not replace them.

Build the model before choosing the mechanism

1. Map protected capabilities

Create an authorisation matrix from the domain, not from framework routes.

Principal Action Resource / container Conditions Expected outcome
Staff member case.view a case in their organisation active employment Allow
Case owner case.update their own open case not locked Allow
Organisation admin user.invite their organisation MFA completed Allow
Any user billing.export organisation billing data no finance role Deny

Include the negative cases deliberately: cross-tenant access, inactive users, deleted/locked resources, delegated access expiry, and privileged actions without step-up authentication.

2. Model the stable domain nouns and relationships

Identify principals, resources, containers, roles/groups, and the relationships that determine access. Use opaque, immutable IDs in policy-facing data; display names, email addresses, and mutable slugs are poor policy identifiers.

For a multi-tenant system, model the tenant/organisation as a first-class container. A resource should have a clear containment path, and a principal’s tenant membership should be supplied from a trusted source. Do not rely on a tenant ID supplied by the browser without resolving and validating it server-side.

3. Identify the enforcement boundaries

Document where checks occur for:

  • single-resource reads, updates, deletes, and downloads;
  • resource creation and listing, against the target container;
  • batch operations, per resource or via a deliberately designed compound decision;
  • asynchronous jobs, webhooks, internal APIs, and service accounts;
  • data stores, object storage, search indexes, and reporting/export paths.

A middleware can be a useful adapter, but it is not the model. The authorisation decision must be close enough to the domain operation that route additions cannot silently bypass it.

4. Define the data contract

Authorisation is only as trustworthy as its inputs. Define the canonical source, freshness expectation, and ownership for each principal attribute, resource attribute, and relationship. Normalise application data into a single request model before evaluating a rule.

Keep principal, action, and resource facts in their respective models. Use request context only for transient, action-specific facts such as an MFA assertion, request time, or an IP/network signal—not as a duplicate source for identity, role, tenant, or resource ownership.

Permission implementation practices

Address listings, creates, and batches deliberately

  • Create: authorise against the verified destination container before creating the resource.
  • List: authorise the container-level list action and apply equivalent tenant/visibility constraints in the query. A list decision alone does not make every item safe to reveal.
  • Batch: evaluate each target resource or use a deliberately designed compound authorisation rule; do not authorise only the first item.
  • Move/share: evaluate all affected source and destination relationships.

Make rule changes a controlled deployment

Version authorisation rules, their supporting model and mapping code, and regression tests together. Validate rules and their configuration in CI. For dynamically managed rules, use staged rollout, approval, rollback, and versioned audit records. Treat model-contract changes as compatibility changes: a change to attributes, relationships, or resource types can alter existing decisions unexpectedly.

Observe decisions without leaking data

Record enough to investigate: request/correlation ID, principal/resource type and opaque IDs where appropriate, action, decision, applicable rule identifiers and version where available, evaluation errors, and latency. Protect logs and avoid raw tokens, sensitive attributes, or full rule payloads unless access and retention are explicitly controlled.

Test strategy

Test authorisation as executable security behaviour, not merely syntax or configuration.

Layer Verify
Decision-model tests intended grants, explicit prohibitions, default deny, and boundary values
Authorisation-boundary tests correct request-to-action mapping, canonical resource resolution, trusted data loading, and error handling
Endpoint/service tests denied calls produce no protected data or side effect; allowed calls reach only valid scope
Data-access tests queries, storage access, and exports retain tenant and visibility constraints
Regression tests known historical incidents and cross-tenant attack cases stay denied
Change tests rule/model migrations preserve decisions intentionally and make changed decisions explicit

For every new permission capability, include at least one must allow, must deny, and must not leak scenario. Test actions—not UI controls—because direct API calls and background execution bypass the UI.

Choose the authorisation mechanism

Use centrally tested application code when the rules are few, stable, local to one service, and readily understood from the domain model. Keep the decision behind a small authorisation boundary rather than copying checks across routes or handlers.

Introduce a policy engine when the model combines roles with ownership, relationships, tenant containment, and attributes; when the same decision must be made in several services; or when policy review, simulation, traceability, or controlled change is a real requirement. A policy engine does not remove the need for trusted data, enforcement at every boundary, query scoping, or governance of who may change access.

Choose based on the behaviour the system needs, not the novelty of the tool.

A common evolution path

Most systems do not need their final permission model on day one. A common progression is:

Simple role checks
        ↓
Central authorisation module or service
        ↓
Resource ownership
        ↓
Tenant isolation
        ↓
Attribute conditions
        ↓
Delegation
        ↓
Shared policies
        ↓
Policy engine, if the demonstrated complexity justifies it

This is not a universal sequence or a maturity scorecard. A product may need tenant isolation before ownership, or never need delegation at all. Treat it as a set of capabilities: adopt the next one only when a concrete product, security, or operational need makes the current model insufficient.

Starting simple is normal. The important discipline is to centralise decisions early enough that the model can evolve deliberately, rather than accumulating inconsistent route-by-route checks.

Operational checklist

Before implementation

  • Define the decision to centralise and the protected business outcome.
  • Inventory all entry points and data/side-effect paths for that domain.
  • Name domain actions, resources, containers, and trusted attributes.
  • Write allow and deny scenarios, including cross-tenant and stale/disabled-user cases.
  • Identify source, freshness, and owner of each authorisation fact.
  • Choose simple central checks or a policy engine based on demonstrated complexity.

Before rollout

  • Authorisation rules and configuration validate in CI.
  • Rule changes have review, audit, and rollback paths.
  • Every protected operation uses the authorisation boundary or an equivalent verified enforcement path.
  • List, batch, create, move, export, background-job, and service-account paths are covered.
  • Decision telemetry captures implementation version and evaluation errors safely.
  • Existing data/query/storage controls still enforce tenant and ownership boundaries.
  • Negative and regression tests prove denial causes neither disclosure nor side effect.

After rollout

  • Inspect allow/deny rates, diagnostics, latency, and unexpected denials.
  • Confirm no route or job bypasses the enforcement boundary.
  • Review exception policies, stale roles, delegations, and privileged access on a defined cadence.
  • Record incidents and confusing access requests as new regression cases or model improvements.

Anti-patterns

  • UI-only permission checks: hiding a button while leaving the API callable.
  • Route-by-route conditionals: duplicating unreviewed logic until equivalent rules disagree.
  • Role explosion: adding a new role for every exception instead of modelling the relationship or rule condition.
  • Tenant IDs from the client: trusting an unverified selector or URL parameter as access proof.
  • Unscoped list authorisation: permitting list but returning objects the caller may not read.
  • Authorisation as a magic boundary: assuming one decision protects data paths it does not govern.
  • Rule/model drift: changing domain relationships or configuration without revalidating affected authorisation decisions.
  • Ignoring decision errors: treating failed or incomplete evaluations as harmless without monitoring their impact.
  • Mutable identifiers in rules: binding access to email addresses, names, or human-facing slugs.
  • No explanation trail: being unable to answer who granted access, why it applied, and when it changed.

References

Categorias
Programming

Building Evolutionary Architectures – Chapter 2: Fitness Functions

Chapter 2 introduces the concept of architectural fitness functions, the mechanism that makes "evolutionary" more than a buzzword.

The origin: borrowing from evolutionary computing

The term comes from genetic algorithm design. In evolutionary computing, a fitness function defines what "better" means so that solutions can gradually emerge through small changes across generations. The classic example: when using a genetic algorithm to optimise wing design, the fitness function assesses wind resistance, weight, air flow, and other desirable characteristics. At each generation, the engineer asks: is this closer to or further away from the goal?

Ford, Parsons and Kua borrow this concept for software:

An architectural fitness function provides an objective integrity assessment of some architectural characteristic(s).

In software, fitness functions check that developers preserve important architectural characteristics; the "-ilities" architects care about: scalability, security, performance, maintainability, resilience.

The core idea

An evolutionary architecture supports guided, incremental change across multiple dimensions. The key word is guided. Without guidance, incremental change is just drift. Fitness functions are what provide the guidance.

The fitness function protects the various architectural characteristics required for the system. These requirements differ greatly across systems and organisations: some require intense security; others require significant throughput or low latency; others need resilience to failure. A crucial early architecture decision is to define which dimensions matter most for a given system, based on business drivers, technical capabilities, and scale.

Why this matters

Most teams have implicit architectural goals: "the system should be fast", "services should be loosely coupled", "we should be secure". The problem is that implicit goals erode. Nobody notices the slow degradation until a characteristic has already failed.

Fitness functions make the implicit explicit. They turn architectural aspirations into verifiable checks. Automated where possible, manual where necessary.

A key insight: improving one architectural dimension can accidentally harm another. Improving performance with caching might harm data freshness or security. Fitness functions act as guardrails that detect these tradeoff violations before they reach production.

Categorising fitness functions

The book defines several dimensions for classifying fitness functions:

Atomic vs Holistic

  • Atomic — tests one particular aspect of the architecture in isolation. Example: a unit test checking for cyclic dependencies in a package, or a code metric that checks cyclomatic complexity.
  • Holistic — tests a combination of architectural aspects, assessing interactions between different concerns. Example: testing the number of concurrent users within a certain latency range while caching is enabled — this simultaneously checks scalability and data freshness. Holistic functions are harder to build but capture what atomic ones miss.

Triggered vs Continuous vs Temporal

  • Triggered — executed in response to a specific event: a developer running a unit test, a CI pipeline stage, a QA person performing exploratory testing.
  • Continuous — constant verification of architectural aspects. Monitoring and alerting are the classic examples. Netflix's Chaos Monkey — which runs in production and randomly terminates instances — is a continuous holistic fitness function that forces teams to build resilient services.
  • Temporal — have a particular time component. Example: a reminder to check whether important security updates have been performed, or a scheduled dependency check that alerts on outdated libraries.

Static vs Dynamic

  • Static — fixed predefined acceptable values. Binary pass/fail (a unit test), or a threshold (latency must be < 200ms).
  • Dynamic — acceptable values depend on context. Acceptable latency might depend on actual system scale; security requirements might vary based on the regulatory environment.

Automated vs Manual

  • Automated — unit tests, deployment pipeline checks, stress tests, chaos engineering. Ideally as much automation as possible.
  • Manual — some things can't be automated (legal approval requirements, certain QA processes). Some things aren't automated yet. The goal is to push the boundary toward automation over time.

What fitness functions look like in practice

Fitness functions encompass existing engineering practices but also extend beyond them:

Category Examples Type
Architecture tests phpat (PHP/PHPStan) or ts-arch (TypeScript) rules checking component dependencies, layer violations, naming conventions, import directionality Atomic, triggered
Code metrics Cyclomatic complexity thresholds, afferent/efferent coupling limits Atomic, triggered
Contract tests API contract verification ensuring requirements are met Atomic, triggered
Security scanning Vulnerability scanning, licence compliance checks for open-source dependencies Atomic, triggered
Performance testing Load tests validating latency SLOs under expected concurrency Holistic, triggered
Monitoring & alerting p99 latency monitors, error rate thresholds, SLO compliance dashboards Atomic/holistic, continuous
Chaos engineering Netflix Simian Army — randomly terminating instances, availability zones, or entire regions Holistic, continuous
Security reviews Quarterly security audits, penetration testing Holistic, manual/temporal
Dependency freshness Scheduled checks for outdated libraries or security patches Atomic, temporal

The best fitness functions are automated and triggered: they give feedback at the point of change, not weeks later. Place them in the deployment pipeline. Fast atomic functions early, slow holistic functions later.

Deployment pipelines as the enforcement mechanism

Fitness functions only work if they're part of the delivery workflow. The deployment pipeline is where they live:

  1. Early stages — fast, atomic checks: architecture tests (phpat, ts-arch), code metrics, linting, security scanning, contract tests.
  2. Middle stages — integration and performance tests, holistic triggered functions.
  3. Later stages / production — continuous monitoring, chaos engineering, temporal reminders.

As Thoughtworks puts it: "creating the desired fitness functions — and including them in appropriate delivery pipelines — communicates these metrics as an important aspect of enterprise architecture."

The four layers of fitness (from NILUS)

A useful framing from practice splits fitness functions across four layers:

  1. Structural fitness — code dependencies, database access patterns, API contracts, service boundaries.
  2. Behavioural fitness — latency, resilience, throughput, consistency, recovery behaviour.
  3. Operational fitness — deployment independence, observability coverage, runbook readiness, SLO compliance.
  4. Semantic fitness — bounded context integrity, event naming quality, policy ownership, domain model consistency.

Most teams start at structural (the easiest to automate) and never reach semantic. But semantic fitness functions (checking that your domain model remains coherent as it evolves) are often the most valuable for long-lived systems.

Systems thinking

Dr. Russell Ackoff's quote captures the deeper point:

A system is never the sum of its parts. It is the product of the interaction of its parts.

Fitness functions that only measure individual components miss the point. The interesting failures happen at integration boundaries — between services, between teams, between intentions and reality. Holistic fitness functions (end-to-end latency, deployment frequency, change failure rate) capture what atomic ones cannot.

How I'm applying this

This connects directly to work I care about:

  • Platform modernisations I've designed and implemented were operational fitness: bringing reliability through automated deployment pipelines, observability and monitoring, and runbook readiness. I just called it "keeping things running."
  • ADRs capture the decisions. Fitness functions verify those decisions are still holding. Decisions and verification go hand in hand.
  • Kent Beck's Test Desiderata is itself a fitness function for test quality — a checklist of characteristics that tests should exhibit (isolated, deterministic, fast, behavioural, structure-insensitive, specific, predictive).
  • DORA metrics (deployment frequency, lead time, change failure rate, MTTR) are fitness functions for delivery capability.
  • Code health metrics (as described in the Loveholidays case from Tropeçando 120) are fitness functions that enabled their AI-first shift — they invested in code health metrics before adopting AI, which is exactly the fitness-function-first approach.
  • phpat (PHP, as a PHPStan extension) and ts-arch (TypeScript) — writing architecture rules as unit tests that run in CI is the purest implementation of triggered atomic fitness functions.

The pattern: define what matters, measure it, enforce it automatically, and revisit periodically. Architecture that can't be verified can't evolve — it can only decay.

Further reading


Part of my reading notes on Building Evolutionary Architectures (Ford, Parsons, Kua).

Categorias
Programming Technology

Building Evolutionary Architectures Notes

Notes

Chapter 1: Software Architecture

Despite our best efforts, software becomes harder to change over time. For a variety of reasons, the parts that comprise software systems defy easy modifications, becoming more brittle and intractable over time. Changes in software projects are usually driven by a reevaluation of functionality and/or scope. But another type of change occurs outside the control of architects and long-term planners. Though architects like to be able to strategically plan for the future, the constantly changing software development ecosystem makes that difficult. Since we can't avoid change, we need to exploit it.

— On Evolutionary Architecture

An evolutionary architecture supports guided, incremental changes across multiple dimensions.

— Definition of Evolutionary Architecture

Related: Ralph Johnson on Architecture (via Fowler, 2003)

These quotes from Ralph Johnson (from [[2026-04-24 - Martin Fowler - Who Needs an Architect|Who Needs an Architect?]]) are foundational to the ideas in this book:

"In most successful software projects, the expert developers working on that project have a shared understanding of the system design. This shared understanding is called 'architecture.' [...] the architecture only includes the components and interfaces that are understood by all the developers."

— Architecture as a social construct, not a diagram.

"There is no theoretical reason that anything is hard to change about software. If you pick any one aspect of software then you can make it easy to change, but we don't know how to make everything easy to change. Making something easy to change makes the overall system a little more complex, and making everything easy to change makes the entire system very complex. Complexity is what makes software hard to change. That, and duplication."

— The fundamental tension that evolutionary architectures try to navigate: change vs complexity.

"Software is not limited by physics, like buildings are. It is limited by imagination, by design, by organization. In short, it is limited by properties of people, not by properties of the world. 'We have met the enemy, and he is us.'"

— The constraint is us, not the technology.

Chapter 2: Fitness Functions

An evolutionary architecture supports guided, incremental change across multiple dimensions.

-- on FItness Functions, chapter 2

The fitness function protects the various archutectural characteristics required for the system. The specific architectural requirements differ greatly across systems and organizations, based on business drivers, technical capabilities, and a host of other factors. Some systems require intense security; others require significant throughput factors.

-- on Fitness Functions, chapter 2

A system is never the sum of its parts. It is the product of the interaction of its parts.

-- Dr. Russel Ackoff

Categorias
Programming

Introduce Parameter Object | Refactoring Patterns

This refactoring pattern involves grouping parameters that naturally go together into a single object. When you see a group of data items that regularly travel together, appearing in function after function, it's a sign they should be combined into a single object.

Check https://rafael.bernard-araujo.com/refactoring-patterns/introduce-parameter-object

There are PHP and Rust implemenation examples.

Categorias
PHP Programming Technology

Building a Serverless PHP Application with Bref, Symfony, and DynamoDB Session Management

Introduction

Serverless apps are fantastic for automatic scaling, but there’s a catch: they expect you to be stateless. Most web applications, however, rely on sessions to remember users and persist state. Traditional PHP session handlers store data on the filesystem, which doesn’t play nicely with ephemeral AWS Lambda instances. Your sessions vanish as soon as the instance disappears.

The usual fix? Fire up a Redis cluster. Works, but suddenly you’ve added infrastructure, ongoing maintenance, and extra costs. Your “serverless” app feels a lot less serverless.

What if we could manage sessions without touching Redis or any other server?

In this post, we’ll show you how to build a truly serverless PHP app using Bref, Symfony, and DynamoDB for session management. Along the way, you’ll see:

  • A custom DynamoDB-backed session handler that replaces filesystem sessions
  • How to deploy your app via Lambda Function URLs using AWS CDK
  • Storing CSRF tokens in DynamoDB for fully stateless operation
  • Single-table design patterns for efficient multi-entity storage

By the end, you’ll know not just how to implement this architecture, but also when it makes sense and what trade-offs you’re accepting.

The Challenge: Sessions in Serverless

Before we dive into the solution, let’s understand why traditional PHP sessions fail in serverless environments.

  1. Ephemeral Storage: Lambda instances can vanish at any time. Writing sessions to /tmp is like storing them in sand. They disappear when the instance is recycled.
  2. No Shared Filesystem: Each Lambda invocation runs on its own instance. User A’s session written by instance 1 is invisible to instance 2. That’s a problem if your user expects to stay logged in.
  3. Horizontal Scaling Woes: Lambda scales horizontally automatically. Without centralized session storage, each instance is isolated. Consistent session management? Forget it.

The Traditional Solution: Redis/ElastiCache

Most serverless PHP guides suggest Redis. While it works, it comes with headaches:

  • Infrastructure complexity: VPCs, subnets, and security groups
  • Maintenance burden: Patching, monitoring, capacity planning
  • Cold start penalty: VPC-connected Lambdas can take 1–2 extra seconds

💡 Better idea: DynamoDB. It’s fully managed, serverless, and scales automatically. No Redis cluster, no maintenance, just pay for what you use.

Books and Authors App (Serverless Style)

Imagine you’re building a multi-tenant SaaS app, like an internal tool for managing books and authors. Each user needs a session, and each organization manages its own data. DynamoDB’s single-table design can elegantly handle all this. Serverless scaling takes care of traffic spikes automatically.

Here’s what this example demonstrates:

  • Multi-entity relationships: Books belong to authors
  • CRUD operations: Create, read, update, and delete across related entities
  • Session-dependent workflows: Adding/editing books requires authentication
  • Real-world complexity: More than a simple counter, less than a full e-commerce platform

Connecting to Real Use Cases

This architecture shines in scenarios like:

  • Unpredictable traffic: Seasonal spikes when authors release new books
  • Session management: Authors need persistent sessions to edit content
  • Cost efficiency: During quiet periods, you pay pennies; during spikes, DynamoDB scales automatically
  • Zero maintenance: No Redis clusters to monitor, no database servers to patch

The book management example proves that this approach isn’t just theoretical: it’s production-ready.

Architecture Overview

To build a serverless PHP application that supports sessions, CSRF protection, and persistent data, we follow a stateful/stateless separation pattern. This makes the architecture scalable, cost-efficient, and easy to maintain.

1. Stateful Layer: Persistent Data

This layer is responsible for storing all data that needs to survive beyond a single Lambda invocation.

  • DynamoDB Table

    • Uses a single-table design to store sessions, CSRF tokens, users, books, and authors.
    • TTL enabled for automatic session expiration.
    • On-demand billing ensures automatic scaling with traffic.
    • Built-in multi-AZ replication provides high availability.
  • Benefits

    • No infrastructure to manage or patch.
    • Automatically scales with unpredictable traffic.
    • Centralized storage simplifies queries and operations.

2. Stateless Layer: Application Logic

This layer runs the application code and handles requests without storing any persistent state locally.

  • Lambda Function

    • Runs PHP-FPM via Bref.
    • Handles HTTP requests directly using a Lambda Function URL (HTTPS endpoint).
    • No VPC required to access DynamoDB, reducing cold start latency.
  • Static Assets

    • Stored in S3 (optionally served via CloudFront) to keep Lambda stateless.
  • Benefits

    • Scales automatically with traffic.
    • Cost-efficient: pay only for actual requests.
    • Stateless logic simplifies deployment and updates.

This design ensures a truly serverless PHP application that handles session state, persistent data, and scalable workloads without the operational overhead of managing Redis or other caching layers.

DynamoDB Session Handler and CSRF Implementation

Session Handler Implementation

In a serverless PHP application, traditional session storage (files or local memory) doesn’t work because Lambda functions are ephemeral. Each invocation may run on a different container, so we need a centralized, persistent session store.

The core of our solution is a custom session handler that implements PHP's SessionHandlerInterface.

How It Works

  • Sessions are stored in DynamoDB instead of the filesystem.
  • Each session has a unique session_id, which becomes the partition key (PK) in DynamoDB.
  • Sessions include the serialized PHP session data and an expiration timestamp (TTL).
  • The handler automatically reads/writes session data on session_start() and session_write_close().

Key Features

  1. Automatic Expiration
    • DynamoDB TTL ensures sessions are removed automatically after expiration.
  2. Atomic Operations
    • PutItem and UpdateItem guarantee consistent writes, even with concurrent requests.
  3. Scalable
    • Can handle thousands of concurrent sessions without extra infrastructure.
  4. Serverless-friendly
    • No local storage, no Redis, fully compatible with Lambda statelessness.

Implementation

<?php

namespace App\Session;

use AsyncAws\DynamoDb\DynamoDbClient;
use AsyncAws\DynamoDb\Input\DeleteItemInput;
use AsyncAws\DynamoDb\Input\GetItemInput;
use AsyncAws\DynamoDb\Input\PutItemInput;
use AsyncAws\DynamoDb\ValueObject\AttributeValue;

/**
 * A minimal DynamoDB-backed PHP session handler using AsyncAws.
 *
 * Table design (single-table compatible):
 *  - PK: "SESSION"
 *  - SK: "SID#<session_id>"
 *  - data: base64-encoded session payload (string)
 *  - expiresAt: unix epoch seconds (number), enable DynamoDB TTL on this attribute
 *
 * Garbage collection is handled by DynamoDB's TTL, so gc() is a no-op.
 */
class DynamoDbSessionHandler implements \SessionHandlerInterface
{
    private const string PK_VALUE = 'SESSION';
    private const string SK_PREFIX = 'SID#';

    public function __construct(
        private readonly DynamoDbClient $dynamoDb,
        private readonly string $tableName,
        private readonly int $ttlSeconds = 3600,
    ) {}

    public function open(string $path, string $name): bool
    {
        // Nothing to do
        return true;
    }

    public function close(): bool
    {
        // Nothing to do
        return true;
    }

    public function read(string $id): string
    {
        $result = $this->dynamoDb->getItem(new GetItemInput([
            'TableName' => $this->tableName,
            'Key' => [
                'PK' => new AttributeValue(['S' => self::PK_VALUE]),
                'SK' => new AttributeValue(['S' => self::SK_PREFIX . $id]),
            ],
            // Strongly consistent read to reduce stale sessions
            'ConsistentRead' => true,
        ]));

        $item = $result->getItem();
        if (!$item || !isset($item['data'])) {
            return '';
        }

        $encoded = $item['data']->getS();
        if ($encoded === null) {
            return '';
        }

        $payload = base64_decode($encoded, true);
        return $payload === false ? '' : $payload;
    }

    public function write(string $id, string $data): bool
    {
        $expiresAt = time() + $this->ttlSeconds;

        $this->dynamoDb->putItem(new PutItemInput([
            'TableName' => $this->tableName,
            'Item' => [
                'PK' => new AttributeValue(['S' => self::PK_VALUE]),
                'SK' => new AttributeValue(['S' => self::SK_PREFIX . $id]),
                'data' => new AttributeValue(['S' => base64_encode($data)]),
                'expiresAt' => new AttributeValue(['N' => (string) $expiresAt]),
            ],
        ]));

        return true;
    }

    public function destroy(string $id): bool
    {
        $this->dynamoDb->deleteItem(new DeleteItemInput([
            'TableName' => $this->tableName,
            'Key' => [
                'PK' => new AttributeValue(['S' => self::PK_VALUE]),
                'SK' => new AttributeValue(['S' => self::SK_PREFIX . $id]),
            ],
        ]));

        return true;
    }

    public function gc(int $max_lifetime): int|false
    {
        // Rely on DynamoDB TTL to expire items; nothing to scan/delete here.
        return 0;
    }
}

Why it matters?

This approach:

  • Keeps your PHP sessions serverless-compatible.
  • Avoids cold-start pitfalls associated with local or in-memory session storage.
  • Provides a reliable, scalable, and fully managed solution for stateful data in a stateless environment.

CSRF Token Storage

In a serverless environment, CSRF tokens must be handled carefully. Because Lambda executions are stateless, tokens cannot be stored in memory or on the filesystem. Instead, CSRF tokens are persisted in DynamoDB alongside session data.

This approach ensures tokens remain valid and verifiable across multiple Lambda invocations.

How CSRF Tokens Are Stored

Each CSRF token is stored as a dedicated item in the DynamoDB table:

  • Tokens are associated with a specific action
  • Each token has a unique identifier
  • An expiration timestamp is stored for automatic cleanup

This makes CSRF token storage consistent, durable, and serverless-compatible.

Data Model

CSRF tokens follow the same single-table design pattern used elsewhere in the application.

Attribute Value
PK CSRF
SK TOKEN#<token_id>
session <session_id>
expiresAt <timestamp>

Using a distinct partition key avoids contention and allows tokens to scale independently from session traffic.

Lifecycle

  1. A CSRF token is generated when a form is rendered.
  2. The token is persisted in DynamoDB.
  3. On form submission, the token is retrieved and validated.
  4. After validation or expiration, the token is deleted or allowed to expire via TTL.

This lifecycle mirrors traditional CSRF handling while remaining compatible with Lambda’s

Implementation

class DynamoDbCsrfTokenStorage implements CsrfTokenStorageInterface
{
    private const string PK_VALUE = 'CSRF';
    private const string SK_PREFIX = 'TOKEN#';

    public function getToken(string $tokenId): string
    {
        $result = $this->dynamoDb->getItem(new GetItemInput([
            'TableName' => $this->tableName,
            'Key' => [
                'PK' => new AttributeValue(['S' => self::PK_VALUE]),
                'SK' => new AttributeValue(['S' => self::SK_PREFIX . $tokenId]),
            ],
        ]));

        $item = $result->getItem();
        return $item['value']->getS() ?? '';
    }

    public function setToken(string $tokenId, string $token): void
    {
        $expiresAt = time() + $this->ttlSeconds;

        $this->dynamoDb->putItem(new PutItemInput([
            'TableName' => $this->tableName,
            'Item' => [
                'PK' => new AttributeValue(['S' => self::PK_VALUE]),
                'SK' => new AttributeValue(['S' => self::SK_PREFIX . $tokenId]),
                'value' => new AttributeValue(['S' => $token]),
                'expiresAt' => new AttributeValue(['N' => (string) $expiresAt]),
            ],
        ]));
    }
}

This ensures CSRF protection works seamlessly across multiple Lambda invocations.

Symfony Configuration

Configuring Symfony correctly is key for serverless PHP apps to work reliably with Lambda, DynamoDB, and Bref. Here’s how we set it up.

1. Session Storage

We replace the default PHP session handler with our DynamoDBSessionHandler:

# config/packages/framework.yaml
framework:
    session:
        handler_id: App\Session\DynamoDBSessionHandler
        cookie_secure: auto
        cookie_samesite: lax
        cookie_lifetime: 3600  # 1 hour

Notes:

  • handler_id points to our custom service.
  • cookie_secure: auto ensures HTTPS enforcement on Lambda URLs or custom domains.
  • cookie_lifetime aligns with DynamoDB TTL for consistency.

2. Service definition

Register the DynamoDB session handler as a Symfony service:

# config/services.yaml
services:
  App\Session\DynamoDbSessionHandler:
    arguments:
      $tableName: '%book_table_name%'
      $ttlSeconds: '%env(default:session_ttl_seconds:int:SESSION_TTL)%'
  • $tableName comes from environment variables to support multiple environments.
  • $ttl matches the session lifetime for automatic garbage collection.
    This configuration tells Symfony to use our custom handler for all session operations. The handler is automatically injected with the DynamoDB client through Symfony's autowiring.

3. RequestContextListener

To handle dynamic Lambda Function URLs, we register a listener:

# config/services.yaml
services:
    App\EventListener\RequestContextListener:
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Purpose:

  • Ensures Symfony’s URL generator produces correct URLs.
  • Sets proper scheme and host for redirects, forms, and CSRF validation.
  • Essential for Lambda Function URLs where host/scheme changes per invocation.

Why It’s Needed

Lambda Function URLs:

  • Provide a direct HTTPS endpoint (e.g., https://xyz.lambda-url.us-east-1.on.aws/)
  • Are dynamic and unknown at build time
  • Require Symfony to know the scheme and host at runtime to generate correct URLs

Without a listener:

  • Redirects may point to HTTP instead of HTTPS
  • CSRF tokens may fail
  • Session cookies might be rejected
  • OAuth or SSO integrations could break

Implementation

<?php

namespace App\EventListener;

use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RequestContext;

#[AsEventListener(event: KernelEvents::REQUEST, priority: 1024)]
class RequestContextListener
{
    public function __construct(private RequestContext $requestContext) {}

    public function onKernelRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $request = $event->getRequest();

        // Force HTTPS for Lambda URLs and set proper context
        if ($request->headers->get('host') && str_contains($request->headers->get('host'), 'lambda-url')) {
            $this->requestContext->setScheme('https');
            $this->requestContext->setHost($request->headers->get('host'));
            $this->requestContext->setHttpPort(80);
            $this->requestContext->setHttpsPort(443);

            $request->server->set('HTTPS', 'on');
            $request->server->set('SERVER_PORT', 443);
            $request->server->set('REQUEST_SCHEME', 'https');
        }
    }
}

The CDK Output Dilemma:

// CDK can output the Lambda URL after deployment
new CfnOutput(this, 'LambdaURL', { 
    value: statelessStack.monolithLambdaFunctionUrl.url 
});
// But this value is only known AFTER deployment completes
// You can't use it as an environment variable in the SAME deployment

💡 Tip: This listener is only necessary if you use the Lambda Function URL as the production endpoint. If you use a custom domain, this can be simplified or skipped.

With this configuration, Symfony becomes serverless-ready, maintaining sessions, CSRF protection, and routing behavior seamlessly while leveraging DynamoDB and Lambda.

Single-Table Design Pattern

All entities (sessions, CSRF tokens, users, books, authors) live in a single DynamoDB table. This simplifies the architecture and enables atomic operations across different entities.

Entity PK SK
Session SESSION SID#<session_id>
CSRF Token CSRF TOKEN#<token_id>
Book BOOK-METADATA AUTHOR#<author_id>#BOOK#<book_id>
Author AUTHOR-METADATA AUTHOR#<author_id>
User USER EMAIL#<email>
  • Why single-table?
    • Reduces infrastructure complexity.
    • Simplifies monitoring and backup.
    • Supports atomic transactions across multiple entity types.
    • Aligns with AWS best practices for DynamoDB.

AWS CDK Infrastructure with Bref

Deploying a serverless Symfony app requires some AWS setup. Using AWS CDK with Bref makes this smooth, maintainable, and repeatable.

Why CDK?

  • Infrastructure as code: Everything is versioned and reproducible.
  • Integration with Symfony: Easy to link environment variables, DynamoDB, and Lambda functions.
  • Bref-friendly: Deploy PHP Lambda layers without manually configuring Lambda functions.

Stateful Stack: DynamoDB Table

import { NestedStack } from "aws-cdk-lib";
import * as ddb from "aws-cdk-lib/aws-dynamodb";

export class BlogAppStatefulStack extends NestedStack {
  public readonly ddb: ddb.Table;

  constructor(scope: Construct, id: string, props: MyNestedStackProps) {
    super(scope, id, props);

    this.ddb = new ddb.Table(this, 'ddb', {
      tableName: `${id}-table`,
      partitionKey: { name: 'PK', type: ddb.AttributeType.STRING },
      sortKey: { name: 'SK', type: ddb.AttributeType.STRING },
      billingMode: ddb.BillingMode.PAY_PER_REQUEST,
      deletionProtection: props.shared.environment === 'prod',
      timeToLiveAttribute: 'expiresAt',
    });
  }
}

Key features:

  • Generic Key Schema: PK and SK enable single-table design
  • TTL Enabled: expiresAt attribute automatically removes expired items
  • Production Protection: Deletion protection enabled for production environments

Stateless Stack: Lambda Function with Bref

import { packagePhpCode, PhpFpmFunction } from "@bref.sh/constructs";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { FunctionUrl } from "aws-cdk-lib/aws-lambda";

export class BlogAppStatelessStack extends NestedStack {
  public readonly monolithLambda: PhpFpmFunction;
  public monolithLambdaFunctionUrl: FunctionUrl;

  private createLambda(props: MyNestedStackProps, staticAssetsBucket: Bucket, ddb: ddb.Table) {
    const lambdaEnvironment = {
      APP_ENV: props.shared.environment,
      APP_SECRET: appSecret,
      ASSET_URL: `https://${staticAssetsBucket.bucketDomainName}/`,
      AWS_LAMBDA_LOG_FORMAT: 'text',
      BOOK_TABLE_NAME: `${props.shared.stackPrefix}-StatefulStack-table`,
    };

    const monolithLambda = new PhpFpmFunction(this, 'App', {
      handler: 'public/index.php',
      phpVersion: '8.4',
      code: packagePhpCode('php', {
        exclude: ['.env.local', 'bin/'],
      }),
      functionName: `${props.shared.stackPrefix}-App`,
      timeout: Duration.seconds(28),
      memorySize: Size.gibibytes(2).toMebibytes(),
      environment: lambdaEnvironment,
    });

    // Create Function URL with no authentication
    const monolithLambdaFunctionUrl = monolithLambda.addFunctionUrl({ 
      authType: lambda.FunctionUrlAuthType.NONE 
    });

    // Grant DynamoDB permissions
    ddb.grantReadWriteData(monolithLambda);

    return { monolithLambda, monolithLambdaFunctionUrl };
  }
}

Lambda Function URL Configuration

Lambda Function URLs provide a simple HTTPS endpoint without needing API Gateway:

const monolithLambdaFunctionUrl = monolithLambda.addFunctionUrl({ 
  authType: lambda.FunctionUrlAuthType.NONE 
});

Benefits of Lambda URLs:

  • Simplicity: Direct HTTPS endpoint without API Gateway complexity
  • Cost: No API Gateway charges
  • Performance: One less hop in the request path
  • Built-in HTTPS: Automatic TLS certificate management

Configuration Options:

  • authType: NONE: Public access (suitable for web applications)
  • authType: AWS_IAM: Requires AWS signature (for service-to-service communication)

Main Stack: Orchestration

export class BlogApp extends Stack {
  constructor(scope: Construct, id: string, props: MyStackProps) {
    super(scope, id, props);

    const stackPrefix = props.shared.envStackPrefix;

    const statefulStack = new BlogAppStatefulStack(
      this, `${stackPrefix}-StatefulStack`, props
    );

    const statelessStack = new BlogAppStatelessStack(
      this, `${stackPrefix}-StatelessStack`, props, statefulStack
    );

    // Output important values
    new CfnOutput(this, 'Lambda', { 
      value: statelessStack.monolithLambda.functionName 
    });
    new CfnOutput(this, 'LambdaURL', { 
      value: statelessStack.monolithLambdaFunctionUrl.url 
    });
    new CfnOutput(this, 'DynamoDb', { 
      value: statefulStack.ddb.tableName 
    });
  }
}

Deployment with CDK

With the infrastructure defined, deploying the application becomes a repeatable and predictable process. This section focuses on how the application is built, deployed, and updated using AWS CDK.

Local Development Environment

Local development mirrors the production setup as closely as possible while remaining lightweight.

  • Docker is used to provide a consistent PHP environment.
  • A Makefile abstracts common commands to reduce cognitive load.
  • Symfony runs locally with the same session and configuration logic used in Lambda.

You can run:

# Pre-requisite - source your aws profile
make up

You can check logs via make logs. And get into the container with make bash. The application will be available at http://localhost:8000, but it might fail to load as there is no existent DynamoDB to connect with. You can check local .env file for environment variables.

Deploying

Deploy the application using standard CDK commands (inside the container):

# Pre-requisite - Bootstrap CDK if this is your first deployment - npx cdk bootstrap aws://<ACCOUNT_ID>/<REGION>
# Install dependencies
npm run deploy

Alternatively, you can use the Makefile command outsite the container:

make deploy

What Gets Created

The deployment creates:

  1. DynamoDB table with TTL enabled
  2. Lambda function with PHP 8.4 runtime (via Bref)
  3. Lambda Function URL for HTTPS access
  4. S3 bucket for static assets
  5. IAM roles and permissions

The output should be similar to:

BlogApp (sandbox-blog-app): deploying... [1/1]
sandbox-blog-app: creating CloudFormation changeset...

 ✅  BlogApp (sandbox-blog-app)

✨  Deployment time: 148.76s

Outputs:
BlogApp.AssetsBucket = sandbox-blog-app-sandboxbloga-assetsbucket5cb76180-5lu45xsqvuym
BlogApp.DynamoDb = sandbox-BlogApp-StatefulStack-table
BlogApp.Lambda = sandbox-BlogApp-App
BlogApp.LambdaURL = https://kiv7utcwku6gihqgs4bfkeuzma0oaylo.lambda-url.us-east-1.on.aws/
Stack ARN:
arn:aws:cloudformation:us-east-1:973974862728:stack/sandbox-blog-app/9ba92580-e50b-11f0-a602-0afffb8dc1a9

✨  Total time: 163.03s

In this case, https://kiv7utcwku6gihqgs4bfkeuzma0oaylo.lambda-url.us-east-1.on.aws/ is the Lambda public URL.

When you access the URL, you will see a log-in form. You can use the "Register" link to create a login. Use it and you will be able to manage Authors and Books. Try to log out and access the pages directly.

Login

Register

Main

Internally it will execute a series of commands:

# clean
npm run clean && \
# execute php packaging including composer install and npm build for symfony
npm run package:sandbox && \ 
# deploy as a sandbox not requiring approval
NODE_ENV=sandbox cdk deploy --require-approval never

There is a prod version executing make deploy:prod.

Testing the Session Implementation

The application includes a test endpoint to verify session persistence:

#[Route('/session-test', name: 'session_test')]
public function test(Request $request): JsonResponse
{
    $session = $request->getSession();
    $counter = $session->get('counter', 0);
    $session->set('counter', $counter + 1);

    return new JsonResponse([
        'message' => 'Session test',
        'session_id' => $session->getId(),
        'counter' => $session->get('counter'),
        'handler' => get_class($session->getMetadataBag()->getMetadata('handler')),
    ]);
}

Test with curl:

# First request creates session
curl -i -c cookie.txt https://your-lambda-url/session-test

# Subsequent requests increment counter
curl -i -b cookie.txt https://your-lambda-url/session-test
curl -i -b cookie.txt https://your-lambda-url/session-test

# outputs
➜ curl -i -c cookie.txt https://your-lambda-url/session-test
{"message":"Session incremented","session_id":"02b0c08e1ccd5f3ea015a06c69e29d11","counter":1,"handler":"App\\Session\\DynamoDbSessionHandler"}%

➜ curl -i -b cookie.txt https://your-lambda-url/session-test
{"message":"Session incremented","session_id":"02b0c08e1ccd5f3ea015a06c69e29d11","counter":2,"handler":"App\\Session\\DynamoDbSessionHandler"}%

➜ curl -i -b cookie.txt https://your-lambda-url/session-test
{"message":"Session incremented","session_id":"02b0c08e1ccd5f3ea015a06c69e29d11","counter":3,"handler":"App\\Session\\DynamoDbSessionHandler"}%

Performance Considerations

Cold Start Optimization

  1. Memory Allocation: Using 2GB memory reduces cold start times
  2. Composer Optimization: --no-dev --optimize-autoloader reduces code size
  3. PHP 8.4: Latest PHP version with JIT compiler support

DynamoDB Performance

  1. Consistent Reads: Ensures session consistency at the cost of slightly higher latency
  2. On-Demand Billing: No capacity planning, automatic scaling
  3. TTL: Automatic cleanup without scan operations

The serverless model's primary advantage is alignment of costs with actual usage, particularly beneficial for applications with variable or unpredictable traffic patterns. However, actual costs vary significantly based on traffic patterns, request complexity, and specific use cases. It's recommended to use AWS cost estimation tools and monitor actual usage to understand the financial impact for your specific application.

Security Best Practices

Session Security

  1. Secure Flag: Ensures cookies only sent over HTTPS
  2. SameSite: Protects against CSRF attacks
  3. Regenerate ID: After authentication to prevent session fixation
framework:
    session:
        cookie_httponly: true
        cookie_secure: auto
        cookie_samesite: lax

DynamoDB Permissions

The Lambda function requires minimal permissions:

ddb.grantReadWriteData(monolithLambda);

This grants only:

  • dynamodb:GetItem
  • dynamodb:PutItem
  • dynamodb:DeleteItem
  • dynamodb:Query
  • dynamodb:Scan

No administrative permissions are granted to the Lambda function.

Limitations

While serverless PHP with DynamoDB sessions offers compelling advantages, it's important to understand the limitations and trade-offs. Here's an honest assessment of where this architecture may not be the best fit:

1. Cold Start Latency

The Reality: Lambda cold starts can add 1-3 seconds to the first request after a function has been idle. In practice this occurs for less than 1% of the calls.

Mitigation Strategies:

  • Provisioned Concurrency: Pre-warm Lambda instances to eliminate cold starts (adds ~$15/month per instance)
  • Keep-Warm Pings: Use CloudWatch Events to invoke functions every 5-10 minutes (adds minimal cost but doesn't help with scaling)
  • Larger Memory Allocation: We use 2GB memory which provides faster CPUs, reducing cold start duration
  • Optimize Code: Minimize dependencies, use PHP preloading, optimize autoloader

When it's acceptable: Background jobs, internal tools, APIs with relaxed SLAs
When it's problematic: User-facing e-commerce, real-time chat, gaming applications

2. Request Timeout Constraints

The Reality: Our configuration uses 28 seconds timeout (API Gateway compatible), though Lambda supports up to 15 minutes, which Lambda URLs supports.

Not Suitable For:

  • Long-running batch jobs: Data exports, report generation, video processing
  • Large file uploads: Direct file uploads over 10MB become unreliable
  • Complex data migrations: Multi-step transformations requiring minutes to complete
  • WebSocket connections: Not supported by Lambda Function URLs (use API Gateway WebSocket instead)

Recommended Alternatives:

  • Keep Lambda URL: If API Gateway specific features are not needed, we can use custom domain with Lambda URLs and process up to 15 minutes
  • AWS Step Functions: Orchestrate long-running workflows across multiple Lambda invocations
  • ECS/Fargate: For truly long-running processes (hours), use containers instead
  • Presigned S3 URLs: For large file uploads, let clients upload directly to S3
  • SQS + Background Workers: Offload heavy processing to asynchronous queues

3. Session Consistency Edge Cases

The Reality: DynamoDB is eventually consistent by default, but we use ConsistentRead: true to mitigate this.

Why We Use ConsistentRead:

'ConsistentRead' => true,  // Ensures we always get the latest session data

Rare Race Conditions:
Even with consistent reads, race conditions can occur when:

  • Simultaneous Writes: User opens multiple tabs, both modify session simultaneously—last write wins
  • Write-then-Read Timing: Session written in one Lambda, immediately read by another—minimal delay possible
  • Cross-Region Scenarios: If using Global Tables, replication lag can cause stale reads in remote regions

Practical Impact: In 99.9% of cases, consistent reads solve the problem. Edge cases typically affect power users opening many tabs or distributed teams across continents.

Mitigation: For critical operations (e.g., payment processing), use DynamoDB conditional expressions to ensure atomic updates and detect conflicts.

4. DynamoDB Costs at Scale

DynamoDB's pay-per-request pricing is cost-effective at low-to-moderate traffic but pricing characteristics change at high scale.

Assumptions

DynamoDB:

  • On-demand billing: $1.25 per million reads/writes
  • 1KB session item size
  • 1 read + 1 write per request

Redis (ElastiCache):

  • t4g.medium: $0.037/hr (~$27/month)
  • 1 node sufficient for low-medium traffic
  • High traffic may require bigger node(s)

Cost Table

Traffic Requests / Month DynamoDB Cost Redis Cost Notes
Low 1M $2.50 $27 DynamoDB far cheaper at low traffic
Medium 10M $25 $27 Costs roughly similar; DynamoDB slightly lower ops
High 50M $125 $108 (cache.m5.large 3 nodes) Redis may become cheaper with large, sustained traffic, but ops complexity rises

When Fixed Infrastructure (like Redis/ElastiCache) May Become More Cost-Effective:

  • Sustained high traffic volumes where fixed costs are fully utilized
  • Long-lived sessions with more reads than writes
  • Advanced caching features needed beyond simple session storage

Hidden DynamoDB Cost Factors:

  • Consistent reads cost more than eventually consistent reads
  • Session writes on every request (even if session data unchanged)
  • AWS free tier limitations after 12 months

Start with DynamoDB for simplicity and operational efficiency. Monitor costs monthly as traffic grows. If costs become a concern at high scale, evaluate whether fixed infrastructure or caching optimizations make sense for your specific use case.


These limitations are not dealbreakers but they're trade-offs. For the right use cases (bursty traffic, cost-sensitive, minimal ops), the benefits far outweigh the drawbacks.

Conclusion

Building serverless PHP applications doesn't require sacrificing familiar frameworks or patterns. By implementing a custom DynamoDB session handler, we achieve:

  • Truly serverless architecture: No Redis, no EFS, pure AWS managed services
  • Production-ready session management: Consistent, scalable, and secure
  • Cost-effective: Pay only for actual usage
  • Developer-friendly: Standard Symfony application with minimal modifications
  • Type-safe infrastructure: AWS CDK with TypeScript
  • Modern PHP: PHP 8.4 with all latest features
  • Local development: Docker-compose for local testing

The combination of Bref for Lambda PHP support, Symfony for application framework, and DynamoDB for stateful storage creates a robust, scalable, and maintainable serverless application architecture.

When Should You Use This Architecture?

Choose this approach when:

  • Traffic is unpredictable or bursty (blogs, seasonal apps, internal tools)
  • Cost optimization matters more than absolute performance
  • Zero operational overhead is a priority
  • You need automatic scaling without capacity planning

Common use cases are:

  • CMS - Blogs, documentation sites, and knowledge bases with infrequent or sporadic traffic, when sudden spikes are scaled automatically and quite periods costs pennies
  • Admin Panels and Internal Tools - Dashboard interfaces, internal reporting tools, and back-office applications with sporadic usage patterns. DynamoDB maintains session state without requiring Redis or similar infrastructure.
  • Multi-Tenant SaaS Applications - B2B platforms where each tenant has independent traffic patterns. DynamoDB's single-table design efficiently manages sessions across all tenants without cross-tenant interference.
  • API Services with Session Requirements - REST APIs that need stateful operations like OAuth flows, multi-step workflows, or temporary data caching. No Redis clusters to maintain, no session cleanup cron jobs to manage. DynamoDB TTL handles everything automatically.
  • Seasonal Applications - Event registration systems, holiday campaign sites, tax filing applications, and other time-bound services.
  • Microservices Requiring Session State - Distributed systems where individual services need temporary state management across invocations.

Consider alternatives when:

  • You require consistent sub-100ms response times
  • Traffic is predictable and sustained at high levels (>10M requests/month)
  • Long-running processes or WebSocket connections are needed

The Bigger Picture

This implementation demonstrates that serverless and stateful aren't mutually exclusive. While serverless advocates often emphasize "stateless functions," real-world applications need state management. The key is choosing the right state storage mechanism, and DynamoDB proves that managed, serverless databases can handle session management as effectively as traditional infrastructure, with far less operational burden.

Whether you're building a content management system, an internal admin panel, or a multi-tenant SaaS application, this architecture provides a production-ready foundation. Start simple, monitor costs and performance, and scale confidently knowing your infrastructure will grow with your application without requiring a dedicated ops team.

Resources

Source Code

The complete source code for this application is available at: rafaelbernard/serverless-php-with-bref-symfony-and-dynamodb-session-management/

For detailed technical implementation notes, test coverage reports, and deployment validation, see IMPLEMENTATION_SUMMARY.md in the repository. This document covers:

  • Complete test suite (112 tests across PHP and CDK)
  • Infrastructure validation details
  • Code quality metrics
  • Deployment procedures and best practices

💡 Bonus: Guide to Custom Domain Configuration with Route53

Lambda Function URLs provide a quick way to expose your Lambda function over HTTPS, but the auto-generated URL (e.g., https://abc123xyz.lambda-url.us-east-1.on.aws/) isn't branded or memorable. But you can add a Simple CNAME Mapping: Direct Route53 CNAME to Lambda Function URL (easiest, limited SSL control).

This is the quickest and easiest method. Just create a CNAME record pointing to your Lambda Function URL. Best for internal tools, prototypes, and non-production environments.

Prerequisites

Before configuring custom domains, ensure you have:

  1. Domain registered in Route53 (or another registrar with ability to update nameservers)
  2. Hosted Zone created in Route53 for your domain

Implementation with CDK

Here's how to add a custom domain CNAME record pointing to your Lambda Function URL using AWS CDK:

import * as route53 from 'aws-cdk-lib/aws-route53';
import * as route53Targets from 'aws-cdk-lib/aws-route53-targets';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

// Assuming you have a Lambda function with Function URL enabled
const myFunction = new lambda.Function(this, 'MyFunction', {
  // ... function configuration
  functionUrlOptions: {
    authType: lambda.FunctionUrlAuthType.NONE, // or AWS_IAM
  },
});

// Get the hosted zone for your domain
const hostedZone = route53.HostedZone.fromLookup(this, 'HostedZone', {
  domainName: 'yourdomain.com',
});

// Create CNAME record pointing to Lambda URL
new route53.CnameRecord(this, 'LambdaUrlCname', {
  zone: hostedZone,
  recordName: 'api', // Creates api.yourdomain.com
  domainName: cdk.Fn.parseDomainName(myFunction.functionUrl), // Extracts hostname from URL
  ttl: cdk.Duration.minutes(5),
  comment: 'CNAME to Lambda Function URL',
});

// Output the custom domain
new cdk.CfnOutput(this, 'CustomDomainUrl', {
  value: `https://api.yourdomain.com`,
  description: 'Custom domain URL for Lambda function',
});

Testing Your CNAME Setup

After creating the CNAME record, verify it works:

# Check DNS propagation
dig api.yourdomain.com

# Test the endpoint
curl -i https://api.yourdomain.com/

# Verify SSL certificate
openssl s_client -connect api.yourdomain.com:443 -servername api.yourdomain.com | grep subject

Expected Results:

  • DNS query returns Lambda Function URL hostname as CNAME target
  • HTTP request succeeds with same response as Lambda URL
  • SSL certificate shows AWS-managed certificate (not your custom domain)
Categorias
Programming

Principles in Refactoring – Slowing Down New Features?

The whole purpose of refactoring is to make us program faster, producing more value with less effort.

and

But I think the most dangerous way that people get trapped is when they try to justify refactoring in terms of "clean code", "good engineering practice", or similar moral reasons. The point of refactoring isn't to show how sparkly a code base is -- it is purely economic. We refactor because it makes us faster -- fastor add features, faster to fix bugs.

-- From Refactoring: Improving the Design of Existing Code (Martin Fowler and Kent Beck), page 56

Categorias
Programming

The Rule of Three

The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.

-- Don Roberts

Categorias
Programming

Domain-Driven Design – DDD

Domain-driven development (DDD) is an approach to software design that focuses on the core domain and the logic that drives a business. The idea is to model the software based on real-world business concepts, ensuring that the code closely reflects the domain it is meant to serve.

Key aspects of DDD include:

  1. Domain Model: A shared understanding of the business logic, defined in terms meaningful to domain experts and developers.

  2. Ubiquitous Language: A common language shared by technical and non-technical stakeholders to describe the domain, ensuring clarity and reducing miscommunication.

  3. Bounded Contexts: Distinct areas within a larger system where a specific domain model applies. Each context can evolve independently while being integrated with others.

  4. Entities and Value Objects: Entities have unique identities, while value objects are immutable and are defined only by their properties.

  5. Aggregates: Clusters of related objects treated as a unit, ensuring consistency in business operations.

  6. Repositories and Services: Repositories handle data access, while services implement business operations that don’t belong to a single entity.

DDD emphasizes collaboration between developers and domain experts to ensure software design mirrors business processes and terminology.

A particularly important part of DDD is the notion of Strategic Design - how to organize large domains into a network of Bounded Contexts. [1]

Why is this important for your business?

The design it proposes puts our focus on the core domain and the business logic, which makes our product relevant and where it differentiates from competitors. The DDD design boosts the understanding of what our application does instead of which technology (framework, dependencies) it uses.

Domain-Driven Design is an approach to software development that centers the development on programming a domain model that has a rich understanding of the processes and rules of a domain. The name comes from a 2003 book by Eric Evans that describes the approach through a catalog of patterns. Since then a community of practitioners have further developed the ideas, spawning various other books and training courses. The approach is particularly suited to complex domains, where a lot of often-messy logic needs to be organized. [1]

We will see more about how this translates to our code as we understand the key aspects to be expanded in future posts.

Related:
[1] Domain-Driven Design by Martin Fowler
[2] Domain-Driven Design on Wikipedia