← All articles
Architecture

Understanding 3-Tier Architecture: What Actually Happens Behind the Scenes?

Three-tier architecture is usually explained as UI → business logic → database. That summary is correct, but it hides almost everything that goes wrong in real systems. Bugs rarely live inside a tier. They live at the boundaries between tiers, where data is serialized, validated, authorized, retried and committed.

This article follows one order request from a button click to a database row and back, and points out where each concern belongs and what fails if you put it in the wrong place. Near the end, I map the same flow onto Dynamics 365 Commerce, where the tiers are easy to see once you know where to look.

Layers and tiers are not the same thing

The two words get used interchangeably, and that causes real confusion, so let's fix the vocabulary first.

  • A layer is a logical separation of responsibility inside your code: presentation, business logic and data access.
  • A tier is a separately deployed part of the system: a browser or device, an application server, a database server.

Three layers do not require three servers. A small application can run its UI, API and business code in one deployable while the database lives on its own server. The logical boundaries still matter, because they are what let you test, change and eventually split the system without a rewrite.

Diagram: three layers (presentation, business, data) shown deployed as two parts or three, with cross-cutting concerns across all.

The layers stay the same whether they are deployed as two parts or three. Security, validation, error handling, logging and the other cross-cutting concerns apply to all of them.

From here on, I use "layer" for the logical split and "tier" when I mean deployment.

The three layers

  • Presentation layer. Web, mobile, desktop or POS interfaces. It collects input, manages presentation state and shows results. It expresses intent ("place this order") and does not make business decisions.
  • Business layer. Application services that apply the rules: order validation, pricing, discounts, tax, inventory checks and orchestration of multi-step processes.
  • Data layer. Repositories or data-access components, and the database behind them. It persists and retrieves customers, products, inventory and orders.

A common point of confusion is where the API or controller sits. In a server-rendered MVC application, the controller is part of the presentation layer. In a single-page or mobile app, the UI runs on the client and the API belongs to the application tier. Decide which model you are in before you decide where validation and mapping live.

Following one request

A customer chooses a product and a quantity, then selects Place Order. Here is what happens.

Diagram: the request path from client through edge, API, business service, repository and database, with where each step can fail.

The business service (highlighted) makes the decisions. The response returns up the same path, and each boundary turns its failures into a clear status code instead of leaking internals.

1. The client sends intent, not facts

The client sends only what it legitimately knows:

{
  "productId": 5001,
  "quantity": 2
}

It does not send the price, the total or the customer's identity. A client can be modified, replayed or replaced by a script, so anything it supplies is a claim, not a fact. The request also carries an idempotency key (more on that below) and an authentication token.

2. The edge terminates TLS and routes the request

The request travels over HTTPS to a load balancer, web application firewall or API gateway, which forwards it to one of several identical application instances. Those instances should be stateless, so any of them can serve any request. This is what lets the application tier scale horizontally. A correlation ID is generated here and attached to the request, so that every log line from every tier can be tied back to this one order.

3. The API deserializes and validates the shape

The API turns the JSON into a request object and checks its shape: productId is present, quantity is an integer, the payload is within size limits. Malformed input is rejected immediately with a clear error.

4. Authentication and authorization

Authentication establishes who is calling. The customer's identity comes from the verified token, never from the request body. Authorization then asks a narrower question: may this caller perform this action on this specific resource? Checking only that someone is logged in, and not that they own the account they are ordering for, is one of the most common API security flaws.

5. The business layer decides

This is where the rules run. The service checks that the customer is eligible and the product is active, reserves stock, calculates price, discounts and tax from server-side data, and creates the order. A thin controller calling a focused service keeps this readable:

[HttpPost("orders")]
public async Task<IActionResult> Create(
    CreateOrderRequest req,
    [FromHeader(Name = "Idempotency-Key")] string key)
{
    var customerId = User.GetCustomerId();  // from the token, never the body
    var result = await _orders.PlaceAsync(customerId, req.ProductId, req.Quantity, key);

    return result.IsSuccess
        ? CreatedAtAction(nameof(Get), new { id = result.Order.Id }, result.Order)
        : Problem(result.Error.Title, statusCode: result.Error.Status);
}

The controller translates between HTTP and the application. It contains no pricing or stock logic. That separation is what makes the rules testable without starting a web server.

The _orders service reaches the controller through dependency injection: the framework supplies it, instead of the controller constructing its own. In turn, the service depends on a repository interface rather than a concrete database class, so tests can substitute a fake. Add a repository only where it creates a useful boundary. If your framework's data-access abstraction already does that job, a generic repository on top is ceremony.

6. The data layer persists, atomically

The repository reads and writes the records. The step that deserves the most care is the stock reservation. A naive version reads the stock level, checks it in code, then writes the new value. Two concurrent orders can both pass the check and oversell the item, because the read and the write are separate steps. Make the check and the update a single atomic operation:

UPDATE Inventory
SET    Reserved = Reserved + @qty
WHERE  ProductId = @productId
  AND  (OnHand - Reserved) >= @qty;
-- 0 rows affected means insufficient stock: return a conflict

Optimistic concurrency with a row version works too. What matters is that the database, not application code, is the arbiter of the race.

The order lines should also store a snapshot of the unit price and tax computed at order time. If the catalogue changes tomorrow, yesterday's orders must not change with it.

7. The response travels back

On success, the server builds a response object, serializes it, and returns 201 Created:

{
  "orderId": 12345,
  "status": "Confirmed",
  "total": { "amount": 1999.00, "currency": "INR" }
}

The UI uses this to show a confirmation. It does not need to know which repository, database or pricing component produced it. That ignorance is the whole point of the architecture.

Contracts, DTOs and serialization

Serialization turns an in-memory object into a representation that can cross a process or network boundary, and deserialization reverses it. A normal method call between two classes in the same process needs neither.

Diagram: client object serialized to a wire format, deserialized to a server DTO, validated and mapped to the domain model.

Only the wire format is shared. Each side owns its own objects and maps to them at the boundary, so neither depends on the other's internals.

The API contract is the agreement between client and server: field names, types, required and optional values, response shape, error format and version behavior. Two practices keep contracts healthy:

  • Use Data Transfer Objects (DTOs) at the boundary. A CreateOrderRequest exposes only productId and quantity. Never bind an incoming payload directly to a database entity. Entities carry internal state, persistence details and sometimes security fields (password hashes, role flags) that clients must neither see nor control. Validate the DTO, then map it to the application model.
  • Plan for change. Adding an optional field is usually compatible. Renaming or removing one breaks older clients. Version your API or adopt an explicit compatibility policy, and keep the error format stable.

The format itself is an implementation choice: JSON for most REST APIs, XML for some SOAP services, Protocol Buffers with gRPC. Pick one clients can consume reliably.

Validation and security belong on the server

Client-side validation improves the user experience, and nothing more. Another client can call your API directly, so the server must check everything again, in three separate steps:

  • Shape validation: the fields exist, have the right types and respect size limits.
  • Business validation: the product is active, stock is available, the customer is eligible.
  • Authorization: the authenticated caller may act on this specific account and resource.

Keeping the three separate keeps the error responses precise: a malformed request, a business rule violation and a forbidden action are different failures and deserve different status codes.

When things go wrong

Errors

Handle each failure at the boundary that can respond safely. Return a stable error code and a clear message to the caller, and record the diagnostic detail internally. Never expose raw database exceptions, stack traces or connection strings, and never swallow an error silently. A standard format such as RFC 9457 problem details keeps clients simple:

{
  "type": "https://example.com/problems/insufficient-stock",
  "title": "Insufficient stock",
  "status": 409,
  "detail": "Requested quantity is not available.",
  "traceId": "4f1c9a2e"
}

The traceId is the correlation ID from step 2. It lets a customer or support agent quote one value and lets you find every related log entry.

Transactions

When the order header, order lines and stock reservation must succeed or fail together, wrap them in one database transaction. Keep that transaction short. A payment provider is outside it: never hold database locks while waiting on a network call. Record the order in a pending state, call the provider, then complete or compensate the order based on the result.

Retries and idempotency

Imagine the server creates the order, but the response is lost and the client times out. The client retries. Without protection, you now have two orders, or two charges.

The fix is an idempotency key: the client generates a unique value per logical operation and sends it with every attempt. The server stores the key in a column with a unique index, together with the result. A repeated request returns the stored result instead of creating a second order, and the unique index makes concurrent duplicates fail safely rather than race.

Connections

Open a database connection late, do the work, and release it promptly so the pool can reuse it. Pooling is efficient, but it needs sensible limits, timeouts and handling of transient failures, or one slow dependency can exhaust every connection.

What the infrastructure adds

So far this has been mostly about layers. The tier view adds its own benefits:

  • Scaling. Stateless application instances behind a load balancer scale out; the database usually scales up or uses replicas.
  • Security. The database sits in a private network and accepts connections only from the application tier. Clients never reach it directly.
  • Fault isolation. A failing web tier should not corrupt data, and a slow database should be contained by timeouts rather than freezing every request.

Some concerns cut across all of it: caching, queues, logging, metrics, tracing and configuration.

  • Caches need deliberate expiry and invalidation rules.
  • Queues suit long-running work and let the API return 202 Accepted, but they introduce duplicate delivery, ordering and retry concerns, so consumers must be idempotent too.
  • Logs and traces must never capture secrets or sensitive customer data.

Seeing it in Dynamics 365 Commerce

Dynamics 365 Commerce is a good real-world illustration, and the mapping is roughly this:

  • Presentation: the POS (Store Commerce or Cloud POS) and the e-commerce storefront.
  • Application: Retail Server and the Commerce Runtime (CRT), which hold the business logic. Customizations extend it through CRT request handlers and triggers, which is exactly where pricing, discount and validation rules are meant to live, not in the POS UI.
  • Data: the channel database, with Headquarters (Finance and Operations) as the system of record. Commerce Data Exchange (CDX) distribution jobs move data between them.
Diagram: D365 Commerce POS, Retail Server with CRT, channel database, offline database and Headquarters.

Customizations belong in the highlighted layer. The offline database and the CDX jobs are where the tier boundaries become visible in practice.

Two behaviors make the tier boundaries visible. First, the POS talks to Retail Server over the network, and when that link breaks, the POS can switch to offline mode with a local database and synchronize later. The network boundary is real, and it fails. Second, if you customize a CRT entity or trigger, you are changing the business layer, and the POS and the channel database both feel it. Knowing which layer owns a rule tells you where to put the fix.

When should a layer become its own service?

Start with clear module boundaries inside one deployable application. Split a layer into a separately deployed service only when there is a concrete need:

  • independent scaling,
  • a distinct security boundary,
  • separate release ownership, or
  • fault isolation.

Every network boundary you add brings latency, monitoring, retries, versioned contracts and new failure modes. Splitting should solve a real operational or organizational problem, not satisfy a diagram.

Key takeaways

  • Layers are logical, tiers are deployment. Use each word for one thing only.
  • The client sends intent. The server decides prices, identity and outcomes.
  • Validate shape, business meaning and authorization separately, always on the server.
  • Make stock checks and updates atomic, and let the database settle races.
  • Keep transactions short, and keep external calls such as payments outside them.
  • Use idempotency keys so a retry never creates a duplicate.
  • Return stable, safe error responses with a correlation ID.
  • Split a layer into a service only when a concrete need justifies the cost.

Three-tier architecture is not valuable because it has three boxes. It is valuable because each boundary is an explicit place to validate, authorize, limit and observe. Get those boundaries right, and each part of the system can change without dragging the others along.

Working on a D365 Commerce implementation, upgrade or integration? Get in touch via the contact section of this site.