Software Architecture

Domain-Driven Design: Generic Subdomains, when to reuse existing solutions instead of building from scratch.

Evaluate generic capabilities using Build vs. Buy criteria and total cost of ownership. Compare authentication options, preserve internal contracts with TypeScript, and learn to reuse without delegating security or business decisions.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

A store that does not need to invent authentication again

The specialist store in our collection wants to improve its recommendations. Before starting, the team proposes building a complete identity system: passwords, access recovery, second factor, sessions, key management, and tools for responding to incidents.

All of that is important. But in this strategy, customers do not choose the store because it created its own authentication technology.

The question is not whether we need to authenticate users. The question is which part we should solve ourselves and which part we should reuse to operate correctly without diverting effort from the business.

Generic Subdomains help identify problems sufficiently well known that existing solutions should be evaluated before building from scratch.

Generic describes the problem, not its importance

A generic subdomain addresses capabilities that do not express this organization's differentiating knowledge and that usually have widely used models or solutions.

Evans recommends separating these problems from the core's specialized knowledge and considering available solutions or published models. He also points out that, however generic they are, they may be essential to the system. DDD Reference: Generic Subdomains, page 41 of the document.

The classification does not imply that a particular solution fits. Nor does it require subscribing to SaaS.

You can reuse a library, operate an existing component, or integrate a managed service. Each alternative distributes development, operations, and responsibility differently.

A brief comparison with the other categories

In our store, the personalized recommendation model contains knowledge intended to differentiate the offering. It is a Core Domain candidate.

The returns operation has particular rules needed to support it. It may be a Supporting Subdomain.

Conventional authentication solves a need common to many products. Here we treat it as a Generic Subdomain.

These are not universal categories for technologies. For an organization dedicated to digital identity, some capabilities the store buys could be part of its strategic knowledge.

Also, Generic Subdomain does not mean a folder, a particular Bounded Context, or a microservice you must deploy.

Complex, critical, and generic at the same time

Authentication can require specialized knowledge and have serious consequences when it fails. Classifying it as generic does not make it simple.

Building a login screen is not equivalent to maintaining a complete identity system. Access recovery, credential protection, sessions, additional factors, and handling abusive attempts must be considered. OWASP documents controls and risks that show this scope. Authentication Cheat Sheet.

Reusing a specialized solution can avoid implementing some of those mechanisms. It does not remove responsibility for configuring it correctly or protecting the application that consumes it.

The practical rule is to separate two decisions: recognizing that a problem is not differentiating and deciding how to meet its requirements. The first informs the second; it does not automatically resolve it.

Build vs. Buy means more than comparing a bill

“Build” and “buy” are extremes within a family of alternatives:

  • Develop and maintain a custom implementation.
  • Integrate a maintained library.
  • Operate an existing product on your own infrastructure.
  • Use a SaaS platform or a managed service.
  • Combine existing components with a limited adaptation.

An open-source option may have no paid commercial license and still need operations, updates, and specialized staff.

A managed option may reduce certain tasks while adding dependency on availability, usage limits, or the supplier's decisions.

There is no right answer for every organization. There are requirements, constraints, and costs that must be compared using evidence.

Prepare an evaluation before watching demos

For the store, we first identify needs:

  • Users with stable identities.
  • Access recovery and appropriate authentication factors.
  • Integration with its applications.
  • Revocation or invalidation according to session requirements.
  • Separation between external identity and the local business account.
  • Operations and failure response.
  • The ability to migrate or reduce dependency if circumstances change.

Then the data processed, access controls, applicable requirements, and contractual responsibilities are analyzed. Regulatory compliance cannot be inferred from a logo or marketing claim.

This article does not recommend specific providers or present current prices. A real selection requires research and testing of available alternatives.

A qualitative evaluation matrix

Criterion             Custom development        Existing solution
Initial time          Implement mechanisms      Integrate and configure
Maintenance           Internal responsibility   Shared, not eliminated
Customization         More potential control    Depends on capabilities and limits
Security              Maintain expertise        Evaluate product and configuration
Operations            Design and sustain them   Depends on who operates it
Exit                  Migrate implementation    Migrate data and dependencies

The matrix does not claim that one column always wins. In particular, potential control does not mean the team has the capacity to maintain it correctly.

First identify requirements that an alternative must not violate. Then compare costs and advantages among the options that satisfy them.

Total cost of ownership

For comparison, define a time horizon and realistic usage scenarios. Consider:

Implementation. Development, integration, testing, and adapting the access experience.

Operations. Monitoring, recovery, support, backups, and availability when they are your responsibility.

Maintenance. Updates, vulnerabilities, API changes, and compatibility.

Consumption and growth. Users, requests, storage, traffic, and features that change costs. Billing methods must be verified in the offering under evaluation.

Risk. Consequences of outages, incidents, and limitations affecting the business. Do not invent a probability figure to fill a sheet.

Exit. Data export, identifier changes, consumer adaptation, and possible account recovery processes.

Opportunity. What the team stops developing while it builds a generic capability.

Do not use a one-time development cost to represent years of operations. Nor compare a license with zero without including the internal work of its alternative.

Keep external identity outside the business model

Even when we integrate a provider, the store retains its own responsibilities: customers, business permissions, orders, and preferences.

Identity provider
       |
       | verification through SDK or documented protocol
       v
Store identity adapter
       |
       | verified external identity
       v
Mapping to local account
       |
       v
Application and business decisions

An external identifier does not have to be the local customer's identifier. It is useful to record the mapping with issuer and subject according to the chosen protocol.

Do not automatically link accounts just because two providers return the same email. A visible attribute does not by itself demonstrate that they should access the same account.

Also, do not confuse authentication with authorization: identifying a user does not prove they can view someone else's order or enter the intranet.

A small internal contract in TypeScript

The following example is educational and intended for a Node.js application. It does not implement login, cryptography, or a complete protocol.

In identity.ts:

export interface ApplicationIdentity {
  readonly userId: string;
}

export interface IdentityVerifier {
  verify(credential: string): Promise<ApplicationIdentity | null>;
}

export interface ExternalVerificationGateway {
  verifyUserCredential(
    credential: string,
    policy: {
      expectedIssuer: string;
      expectedAudience: string;
    },
  ): Promise<unknown>;
}

export interface LocalAccounts {
  findLinkedAccount(
    issuer: string,
    subject: string,
  ): Promise<{ userId: string; enabled: boolean } | null>;
}

ExternalVerificationGateway is an illustrative port, not the name of a real API. Its implementation must use the provider's official SDK or a documented protocol.

That port's contract requires verifying the user credential, its purpose, and the protocol requirements before returning a result. Decoding a JWT, reading a cookie, or trusting browser data is not enough.

For our example, the gateway normalizes the verified response to an object with active, issuer, subject, audience, and expiresAtSeconds. Those names are our own teaching representation, not a claim that every provider returns that JSON.

As a reference for a real option, OAuth Token Introspection allows querying a token's active status and metadata through a protected endpoint. Its use requires applying the protocol's conditions and not turning any active token into a user identity. RFC 7662.

Adapt the verified result to the local account

The following block complements the previous file:

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null &&
    !Array.isArray(value);
}

export class ExternalIdentityAdapter implements IdentityVerifier {
  constructor(
    private readonly gateway: ExternalVerificationGateway,
    private readonly accounts: LocalAccounts,
    private readonly issuer: string,
    private readonly audience: string,
    private readonly nowSeconds: () => number,
  ) {}

  async verify(credential: string): Promise<ApplicationIdentity | null> {
    if (credential.trim().length === 0) return null;

    const raw = await this.gateway.verifyUserCredential(credential, {
      expectedIssuer: this.issuer,
      expectedAudience: this.audience,
    });

    if (
      !isRecord(raw) ||
      raw.active !== true ||
      raw.issuer !== this.issuer ||
      raw.audience !== this.audience ||
      typeof raw.subject !== "string" ||
      raw.subject.length === 0 ||
      typeof raw.expiresAtSeconds !== "number" ||
      !Number.isSafeInteger(raw.expiresAtSeconds) ||
      raw.expiresAtSeconds <= this.nowSeconds()
    ) {
      return null;
    }

    const account = await this.accounts.findLinkedAccount(
      this.issuer,
      raw.subject,
    );

    if (!account || !account.enabled) return null;
    return { userId: account.userId };
  }
}

Issuer and audience values come from controlled configuration. The clock is injected to test boundaries; in production it must come from a trustworthy server source.

Field checking does not replace the gateway's security verification. The adapter assumes that component has validated what the protocol requires, including signature where applicable, purpose, and validity conditions.

In our normalized contract, the audience is a single string. If the provider uses multiple audiences, the gateway must interpret them correctly and normalize only after checking the expected one.

A valid credential without a linked account does not automatically create an account. Registration and linking need a separate process we have not implemented.

External failure does not authorize access

If the gateway fails because it is unavailable, the exception propagates. The entry layer must distinguish this technical failure from an invalid credential without allowing access as an alternative.

We do not show account persistence, gateway transport, verification caching, or session management. Those decisions require configuring and integrating the chosen solution.

The snippet's purpose is to demonstrate that the application receives userId, not a provider object with assumed permissions.

A local test does not certify authentication

This proposed test uses Node.js built-in APIs and assumes TypeScript compilation to JavaScript ESM. It has not been run as part of the article.

import test from "node:test";
import assert from "node:assert/strict";
import { ExternalIdentityAdapter } from "./identity.js";

test("rechaza una credencial expirada sin buscar la cuenta", async () => {
  let accountLookupCalled = false;

  const adapter = new ExternalIdentityAdapter(
    {
      async verifyUserCredential() {
        return {
          active: true,
          issuer: "https://identity.example",
          subject: "external-user-1",
          audience: "shop-api",
          expiresAtSeconds: 100,
        };
      },
    },
    {
      async findLinkedAccount() {
        accountLookupCalled = true;
        return { userId: "user-100", enabled: true };
      },
    },
    "https://identity.example",
    "shop-api",
    () => 100,
  );

  assert.equal(await adapter.verify("test-credential"), null);
  assert.equal(accountLookupCalled, false);
});

It is an adapter test with a substituted gateway. It does not test cryptography, provider communication, or actual configuration.

Integration verification must cover valid, invalid, revoked, or expired credentials, incorrect issuer and audience, unlinked subjects, disabled accounts, and provider failures, according to the chosen system's guarantees.

Do not log credentials, tokens, or passwords to debug those tests. And do not use production users or secrets to experiment.

What changes when using an existing solution

The store stops implementing certain specialized mechanisms, but still has work to do:

  • Choose and configure the appropriate protocol.
  • Protect administrative secrets and credentials.
  • Maintain the adapter and its dependencies.
  • Define application permissions.
  • Manage account linking and closure.
  • Establish how it operates when the provider does not respond.
  • Review data processing and applicable conditions.

A small boundary can limit propagation of the external model. It does not eliminate all dependencies: recovery processes or session options may continue to shape the experience.

Do not build a universal abstraction promising effortless exchange of any provider. Represent the needs you have and document what is not interchangeable.

When development may be justified

A generic problem does not require outsourcing. Operational, integration, connectivity, or data control restrictions may make a particular alternative unsuitable.

Implementing a small piece may also be reasonable when integrating a complete system adds more cost than solving the known scope.

However, “we need a different screen” does not prove a need to implement password storage, recovery, and token verification from scratch.

Distinguish customizing the experience, integrating an existing component, and developing a complete identity platform. The decision must respond to verifiable needs and the team's capacity to sustain it.

Reuse does not prevent developing your own code. Building does not require inventing cryptographic mechanisms.

A Build vs. Buy decision that can be reviewed

A useful record for the store might document:

Capability: conventional authentication.
Strategic role: generic in the current offering.
Mandatory requirements: identified protocols, security, data, and operations.
Alternatives: an existing component operated internally or a specialized service, compared with custom development.
Evaluation pending: integration tests, costs at different volumes, and exit procedure.
Local boundary: identity contract and independent business accounts.
Review conditions: unmet requirements, price or limit changes, and migration difficulties.

This is not an actual provider selection. Concrete information about alternatives and requirements is still missing.

Review conditions help avoid both forgotten dependencies and an impulsive migration triggered by a single bill.

Another application: an educational platform

A platform focused on practice and feedback can use existing services for authentication, email, and storage.

This lets it focus part of development on conceptual errors and activities that help learning. It does not make the other capabilities irrelevant.

Email must respect recipients, permissions, and preferences; accepting a send request does not mean the message arrived. Storage must apply authorization and prevent private files from accidentally being published.

The platform retains its own educational rules while using common mechanisms. It can keep small local contracts for sending and document access without copying every provider detail.

If it sells specialized email delivery technology in the future, that capability's classification may change. The label depends on its strategy, not the API's name.

Third example: reuse a library instead of a service

A product needs to generate documents in a known format. It can evaluate a maintained library before building its own engine or adding a remote service.

The library introduces dependency, update, and unsupported-format risks; the service additionally introduces networking, limits, and external document processing.

The appropriate alternative depends on scope and data. This example shows that Build vs. Buy is not limited to “our code or SaaS.”

All three options require tests using real test documents and verifiable expectations, not just a simple demo.

Mistakes to avoid

Generic means cheap. A critical capability may need considerable investment even if it does not differentiate.

The provider handles all security. The application remains responsible for its configuration and permissions.

The library is free, so it has no cost. There are operations, maintenance, and version dependencies.

The best-known service fits by definition. Specific requirements and limits must be verified.

The SDK defines the domain. An external dependency should not automatically become the customer model or business policy.

AI can build it in an afternoon. Generating code does not cover maintenance, incidents, or security guarantees.

Use AI to support evaluation

For Cursor, Claude, or Codex, provide requirements, constraints, and available evidence.

To research alternatives:

Find current alternatives for this generic capability. Use official documentation and distinguish verified capabilities from open questions. Do not invent prices, certifications, or limits. Compare integration, operations, data, and exit according to these requirements.

To design the boundary:

Propose a minimal internal contract for the identity our application needs. Keep external issuer and subject separate from the local user. Use an SDK or documented protocol to verify credentials; do not implement cryptography or accept decoded claims as proof of identity.

To review a decision:

Review this Build vs. Buy comparison. Identify omitted costs, provider dependencies, and requirements without evidence. Separate facts, estimates, and hypotheses. Do not present an automatic score as security or investment approval.

Final selection requires human judgment and review by the responsible people. Do not send sensitive data or credentials to analysis tools to complete a comparison.

Exercises

1. The customized screen

The team wants a login screen with the store's visual identity and concludes it must build all authentication. What alternatives are missing?

2. The active token

A service returns that a token is active. The code grants access to any user presenting it. What checks might be missing?

3. The alternative without a paid license

An existing component has no usage charge. Is that enough to conclude its total cost will be lower?

Reasoned solutions

1. Evaluate customization and integration of existing solutions without assuming that the visual interface requires custom identity mechanisms. Check what each alternative permits and which actual requirements remain unmet.

2. Verify purpose, issuer, audience, and protocol conditions, as well as mapping to an enabled local account. An active token may not represent a valid user credential for this application; identity also does not mean authorization over every resource.

3. No. Include infrastructure, updates, support, security, operations, and exit, in addition to implementation time. The absence of a fee does not eliminate these costs.

Reuse to focus effort better

Identifying a Generic Subdomain lets you ask whether an existing solution meets the need before building it from scratch.

The decision is sound when it responds to clear requirements, compares full costs, and maintains an understandable boundary with the business's own model.

It is not a matter of outsourcing everything common. It is a matter of solving it with sufficient guarantees and responsibility the organization can sustain.

Loading conversation…

Keep learning