Start by settling two things before you draw a single box: what the app must do on day one, and which operational constraints you can't escape (team size, budget, deployment target). The architecture itself follows from those answers. For most Java web applications in 2026, a pragmatic default is a layered modular monolith built with Spring Boot, organized around business capabilities, with a clean separation between an HTTP-facing web layer, a service/domain core, and a persistence adapter. Only split into distributed services once you have a concrete reason, such as independently scaling a workload or separating teams that keep colliding in the same codebase.

That default is not dogma. This guide walks through how to arrive at it, how to define boundaries, how to choose data and interaction patterns, and how to test and evolve the result without a rewrite. The order matters: requirements and constraints first, boundaries second, technology third, operations throughout.

Start With Drivers, Not Frameworks

An architecture is a set of decisions that are expensive to reverse. If you pick frameworks first, you end up with a stack looking for a problem. So begin with the forces that will actually shape the design:

Functional scope. Which capabilities are core to the business and which are supporting? A checkout flow, a reconciliation engine, and a reporting module have very different consistency and throughput needs even if they live in one deployable.

Quality attributes. Write down concrete targets rather than adjectives. "Fast" is useless; "p95 response under 300 ms for the catalog read path at 500 requests per second" is a design constraint. Same for availability windows, recovery point objective (how much data you can lose), recovery time objective (how long downtime is acceptable), and data retention obligations.

Team topology. Three engineers and three dozen engineers need different architectures. Conway's Law is descriptive, not a law you fight: your system will tend to mirror your communication structure. If two teams own two capabilities, a module boundary with a clear interface is cheap; a shared database schema is not.

Deployment and compliance constraints. On-premises hosting, a specific cloud region, data residency rules, or an existing identity provider all eliminate options early. Find these out before you fall in love with a design.

Change expectations. Which parts will churn weekly, and which should be stable for years? Architecture should make the high-churn areas cheap to modify and the stable areas hard to accidentally break.

The output of this step is a short, written list: two or three core capabilities, three to five measurable quality attributes, and the hard constraints. This becomes the yardstick you test every later decision against. It's also the document that saves you in six months when someone asks why the system is shaped the way it is.

Choose a Structural Style and Commit to It

With drivers in hand, select the coarse structure. Three common shapes cover most Java web applications:

Layered monolith. One deployable, organized into horizontal layers (web, service/domain, persistence). Simplest to build, test, and operate. The failure mode is the "big ball of mud" where layers blur and everything calls everything.

Modular monolith. One deployable, but internally partitioned into modules aligned to business capabilities, each with an explicit public interface and private internals. You get most of the maintainability benefits of services without distributed-systems overhead. This is the sensible 2026 default for most teams.

Service-oriented or microservices. Multiple deployables, each owning a capability and its data. Justified when you have independently scaling workloads, distinct release cadences enforced by separate teams, or hard isolation requirements (for example, a payment path that must be auditable in isolation). The cost is real: network failures, eventual consistency, distributed tracing, deployment orchestration, and a much higher operational floor.

A useful heuristic: pick the least distributed structure that satisfies your quality attributes and team topology. If you can't name the specific problem that distribution solves, don't distribute. Start with a modular monolith and treat module boundaries as the seams along which you could later extract a service—this preserves optionality without paying the distributed tax now.

Whatever you choose, commit to it in writing and enforce the boundaries mechanically. Architecture that exists only in a diagram decays in weeks.

Define Layers and Assign Responsibilities

Inside the deployable, define layers with strict rules about what may call what. A dependable Java layout looks like this:

Web/API layer. HTTP controllers or message listeners. Its job: parse input, validate shape and authentication, translate to a domain call, and translate the result back to a response. It should contain no business rules. Keep it thin, and let it depend inward on the domain.

Application/service layer. Use-case orchestration: "place order," "renew subscription." It coordinates domain objects and outbound ports (repositories, gateways), manages transactions, and enforces application-level authorization. One public method per use case is a good discipline.

Domain layer. The business model: entities, value objects, domain services, invariants, and pure business rules. This layer should be the most heavily tested and the least dependent on frameworks. If you can unit-test your pricing logic without a Spring context, you've done this right.

Persistence/infrastructure layer. Adapters that implement the ports the domain defines: database repositories, HTTP clients to external systems, message publishers. Frameworks like JPA or messaging libraries live here, not in the domain.

Cross-cutting concerns. Logging, metrics, tracing, security, and configuration. Apply these via framework mechanisms (filters, interceptors, aspects) so they don't leak into business code.

The dependency rule is the whole point: source-code dependencies point inward toward the domain. The domain knows nothing about HTTP, SQL, or Kafka. Infrastructure depends on the domain's interfaces, not the reverse. This is the essence of ports-and-adapters (hexagonal) architecture, and in Java it's usually expressed as an interface in the domain package implemented by a class in an infrastructure package—often wired together with dependency injection.

Enforce the rule with tooling rather than discipline alone. ArchUnit is the standard Java library for writing tests that assert package dependencies—for example, "no class in ..domain.. may depend on ..web.. or jakarta.persistence..." These tests run in CI and fail the build when someone takes a shortcut.

Set Module Boundaries Around Business Capabilities

Within a modular monolith, partition by business capability, not by technical type. "Billing," "Catalog," and "Identity" are better modules than "Controllers," "Services," and "DAOs." Each module has a public API package (interfaces and DTOs other modules may use) and an internal package that nothing outside may touch.

Two rules make modular monoliths work:

1: No cross-module access to internals. Module A talks to module B only through B's public API. Enforce with ArchUnit or by packaging (Java's module system can help, though many teams find ArchUnit simpler in practice). 2: Data ownership. Each module owns its tables. Cross-module reads go through the owning module's API, not direct SQL joins into another module's schema. This is the hardest rule to hold, and the one that most determines whether you can ever extract a service.

Model boundaries after the nouns your domain experts use in conversation. If two capabilities change together constantly, they're probably one module. If a single module has grown to hold unrelated concerns that change for different reasons, it's a candidate for a split. Aim for modules a single team can hold in its head—typically a handful of capabilities per module.

A practical test: can you describe each module's responsibility in one sentence without "and"? If you need three "ands," you likely have three modules.

Design the Domain and Data Access Deliberately

Data design is where architectures quietly succeed or fail. A few decisions carry most of the weight.

Aggregate and transaction boundaries. Group entities that must change together inside one transaction. Keep transactions short and scoped to a single module's data. If a use case seems to need a transaction spanning two modules, that's a signal to rethink the boundaries or introduce an explicit coordination mechanism rather than reaching across schemas.

Persistence approach. JPA/Hibernate suits rich domain models with complex relationships and modest write volumes. For read-heavy, high-throughput paths, a thinner approach (Spring Data JDBC, JdbcClient, jOOQ) often serves better. It's entirely reasonable to mix: JPA for transactional writes in one module, plain SQL for reporting queries. Don't let a single tool dictate your entire data strategy.

Schema migrations. Use a versioned migration tool (Flyway or Liquibase) from day one, and never let the application alter production schema automatically. Migrations are code, reviewed and versioned.

Transactional boundaries and idempotency. Wrap each use case in a single transaction where you can. For operations triggered by messages or external callbacks, make them idempotent so retries don't double-apply. This matters even in a monolith and is essential the moment you split anything.

Read models for expensive queries. Dashboards and search often want shapes the write model doesn't provide. Maintaining denormalized read tables, materialized views, or a caching layer is normal. Treat them as derived data you can rebuild, not sources of truth.

The principle: separate the consistency requirements of transactional writes from the performance needs of reads, and choose tools per path rather than per application.

Decide How Components Communicate

Even in a monolith, components communicate, and the same choices recur when you distribute. Make the mode explicit per interaction:

In-process calls. The default inside a modular monolith. Fast, transactional, easy to debug. Use them unless you have a reason not to.

Synchronous remote calls (HTTP/gRPC). Necessary when a dependency is a separate deployable, such as a third-party payment API. Always add timeouts, retries with backoff and jitter, and circuit breakers. A synchronous call chain that fails at the far end must fail fast, not hang. A circuit breaker that opens after sustained errors and probes recovery is standard; Netflix's Resilience4j or the Spring Cloud circuit-breaker abstraction covers it.

Asynchronous messaging. Use when the caller doesn't need an immediate answer, or when work is long-running or must survive a crash. A message broker (Kafka for high-throughput event streams and durability; RabbitMQ for flexible routing; or a cloud-native queue) decouples producer from consumer. The trade-off is eventual consistency and the need to design for duplicate delivery, ordering, and poison messages.

Event-driven decoupling inside a monolith. You can get the design benefits of events without a broker by publishing domain events in-process and handling them synchronously within the transaction or asynchronously after commit. When you later extract a service, those events can move to a broker with minimal change to the domain.

The pattern that keeps this manageable: define outbound dependencies as interfaces (ports) in the domain and implement them as adapters—an HTTP client, a broker publisher, an in-memory queue. The domain says "publish an OrderPlaced event"; the adapter decides whether that's a broker topic today or an in-process listener.

Wire in Security, Configuration, and Observability From the Start

Retrofitting these is far more expensive than including them from the first sprint.

Security. Authenticate at the edge and authorize at the use-case layer. For token-based auth, prefer a standard like OAuth 2.1 / OpenID Connect over hand-rolled schemes, delegating to an established identity provider. Enforce authorization on each use case, not just the controller, so every path is covered. Set secure defaults for cookies and sessions, validate and encode all external input, and scope database credentials narrowly. Be careful with the OWASP-style classics: injection (parameterized queries and validated input), broken object-level authorization (check ownership, not just role), and insecure deserialization. Keep secrets out of source; use a secrets manager or environment injection, and rotate them.

Configuration. Externalize configuration per environment; never bake endpoints or credentials into the artifact. Use profile- or environment-based configuration with a clear precedence order and schema-validated properties so a missing key fails at startup instead of in production.

Observability. Structured logs with a correlation identifier threaded through requests, metrics for latency and error rates on the use cases that matter, and distributed tracing (for example, OpenTelemetry) once you have more than a couple of hops. Expose health and readiness endpoints for the orchestrator. Define the small set of signals you'd page on—error rate, latency, saturation, queue depth—before your first incident, not after.

These are architectural concerns because they cut across every layer. The way to keep them out of business code is to implement them at the framework boundary: filters, interceptors, and aspects for cross-cutting behavior, dedicated classes for security policy, adapters for instrumentation.

Enforce the Architecture With Tests and CI

An architecture you can't check is a suggestion. Build the checks in from the start:

Dependency rules. ArchUnit tests asserting package and layer dependencies. This is cheap and catches the erosion that turns modular designs into mud.

Domain tests without infrastructure. Your business logic should be testable with plain JUnit and in-memory fakes for the ports, no database or container required. If a test needs a running database to verify a pricing rule, the logic leaked into infrastructure.

Adapter and integration tests. Test persistence adapters against the real database technology (often via Testcontainers) to catch dialect and mapping issues that fakes miss. Test outbound HTTP adapters against a stubbed server.

End-to-end smoke tests. A thin set of critical-path tests through the real HTTP interface, kept small to stay fast.

CI gates. Compile, run unit and architecture tests, run integration tests, and build a container image on every merge. Fail the build on architecture violations. Add static analysis (SpotBugs, SonarQube, or Error Prone) with a curated ruleset rather than an overwhelming one that people disable.

A practical way to check success: try to violate the layering on purpose in a branch and confirm CI rejects it. If it passes, your guardrails don't exist.

Design the Build, Container, and Deployment Path

Architecture extends to how the artifact runs. For a typical Java web application:

Build a runnable artifact. Spring Boot's executable JAR or a WAR into a servlet container both work; the executable JAR is the common default. Pin your JDK version (Java 21 LTS is a safe baseline for 2026; verify current support windows before committing). Use a dependency-management approach that pins transitive versions, and keep the build reproducible.

Containerize with a layered image. Multi-stage builds keep the image lean. Copy dependencies in a separate layer from application classes so code changes don't invalidate the dependency cache. Run as a non-root user, set memory limits that match the JVM's container-aware settings (heap as a fraction of the limit, leaving room for metaspace and the rest), and handle graceful shutdown so in-flight requests and messages complete.

Configuration and orchestration. Keep environment-specific values outside the image, and let your orchestrator (Kubernetes or a platform service) supply them. Define readiness and liveness probes against your health endpoints. Match your scaling strategy to the workload: horizontal replicas for stateless web nodes, and careful handling for anything stateful like scheduled jobs—use leader election or a single designated scheduler to avoid duplicate execution.

Migrations at deploy time. Run database migrations as an explicit step in the pipeline, ordered before the new application version starts, and design them to be backward compatible (see the next section) so old and new instances can run side by side during a rolling deploy.

Plan for Change: Extraction, Evolution, and Failure

The architecture isn't finished at launch; it's finished when it can evolve without a rewrite. Build these capabilities in:

Extraction seam. Because modules own their data and communicate through ports, extracting a module into a service later is mostly plumbing: replace an in-process interface with a remote client and stand up a new deployable. The rule that makes this possible is the one from earlier—no cross-module table access. If you've held that line, extraction is a project; if you haven't, it's a crisis.

Backward-compatible migrations. Use the expand/migrate/contract pattern: add new columns and code paths, migrate data in the background, switch reads and writes, then remove old ones in a later release. Never drop a column in the same release that stops writing to it. During a rolling deploy, two application versions coexist, and both must work against the current schema.

Failure design. Assume every dependency can be slow or unavailable. Set timeouts on everything, decide per interaction whether to fail fast or degrade gracefully, and make retries safe. For outbound calls that must not be lost, use the transactional outbox: write the intent to publish a message inside the same database transaction as the business change, then a relay publishes it reliably. This is the pattern that makes "send an email" and "record the order" atomic enough to trust.

Capacity and load. Before you scale out, run a load test against a realistic read/write mix and measure. Remember that scaling stateless replicas doesn't scale a shared database; find the actual bottleneck (connection pool, query plan, lock contention) before adding hardware.

A concrete worked example of the evolution path: you start with a modular monolith where Billing and Identity are modules. Billing grows a workload that spikes independently at month-end, saturating the shared database. Because Billing owns its tables and exposes only an API, you extract it to its own deployable with its own database, route calls through a remote client, and move its event publishing onto a broker. The domain code for the business rules didn't change—only the adapters did. That's the payoff of the layout described above.

Prerequisites Before You Build

Before writing code, have these in hand; skipping them is how projects discover their constraints in month four:

Written drivers: core capabilities, 3–5 measurable quality attributes, hard constraints. A chosen structural style (layered monolith, modular monolith, or services) with a one-paragraph justification. The module map: each module's name, single-sentence responsibility, owned tables, and public API surface. The layer and dependency rules you intend to enforce, and the tool (ArchUnit or equivalent) that will check them. The persistence and migration tooling, and the data-ownership rules. The communication modes per interaction (in-process, synchronous remote, asynchronous), with timeouts and retry policy. Security, configuration, and observability approach, plus the identity provider or token scheme. The build, container, and deployment pipeline skeleton, including a migration step and health probes. The test strategy and CI gates, including a deliberate architecture-violation check.

Build It in Order

Work in dependency order so each step is testable on its own. Each step names what "done" looks like.

1: Scaffold the deployable and layers. Create the project with packages for web, application, domain, and infrastructure, and wire a single "hello" use case end to end. Success check: the endpoint returns a response built by an application service calling a domain object; the domain package builds with no framework imports.

2: Define the first module's boundary. Write the public API interface and DTOs for one core capability, plus the ArchUnit rule that forbids external access to internals. Success check: the architecture test fails if you temporarily call an internal from outside the module.

3: Implement the domain and its ports. Put business rules in domain classes with plain unit tests and in-memory fakes for the outbound ports. Success check: the use-case tests run with no database or Spring context.

4: Add persistence and migrations. Implement a repository adapter, write the Flyway/Liquibase migration, and test the adapter against the real database (Testcontainers). Success check: integration tests pass against a fresh container with migrations applied.

5: Add transactions, idempotency, and the outbox if needed. Wrap the use case in a transaction; make message-triggered operations idempotent; add a transactional outbox for any must-deliver message. Success check: a forced duplicate of a message-driven operation changes state once, not twice.

6: Layer in security. Authenticate at the edge, authorize in the use case, and keep secrets external. Success check: an unauthorized call fails at the use case, not merely in the controller.

7: Add observability. Structured logs with a correlation ID, metrics on the critical use cases, and health endpoints. Success check: you can trace one request's log line through its use-case calls.

8: Containerize and run the pipeline. Build the layered image, wire configuration by environment, add health probes, and set the pipeline to run migration, then deploy. Success check: a rolling deploy of two versions against the current schema succeeds with no downtime and no schema errors.

9: Repeat steps 2–8 per module, then add load tests against a realistic mix. Success check: the measured bottleneck is identified rather than guessed.

When to stop and call for specialized help: if your security requirements are regulatory or the use case touches payment card data, work with a security or compliance specialist before launch rather than after. If a deployment is failing in ways you can't explain after timeouts, retries, and resource limits have been ruled out, that's a signal to bring in platform or database experts—guessing at production infrastructure is how small issues become outages.

What Goes Wrong and How the Rules Help

Most architecture failures are predictable. A few common ones and the check that catches them early:

The layered design that became a ball of mud. Business logic leaks into controllers and repositories over months. Fix upstream: ArchUnit dependency rules in CI.

The "distributed monolith." Services split, but they share a database and call each other synchronously in chains, so a single failure cascades. Fix upstream: the data-ownership rule and explicit circuit breaking on every synchronous remote call.

The anonymous module. A module without a clear public API grows tendrils into everything. Fix upstream: one-sentence responsibility per module and enforced API packages.

The lost message. An operation writes to the database, then publishes to a broker that's briefly down. Fix upstream: the transactional outbox.

The migration that breaks a rolling deploy. A column is dropped while old instances still write to it. Fix upstream: expand/migrate/contract and a pipeline step that applies migrations before app start.

These are not edge cases; they're the default trajectory without guardrails. The rules above are cheap to install and expensive to retrofit.

Common Questions

Do I always need a modular monolith? No. A small prototype with one team can start as a simple layered monolith and add modules when a second capability appears. The rules that matter most—inward dependencies, data ownership, explicit ports—cost little to adopt early and are painful to add later.

Should I use microservices from the start? Only if you can name the specific quality attribute or team constraint that requires them. Otherwise, the operational and debugging overhead outweighs the benefit for most projects.

Which Java and Spring versions should I target? Choose a currently supported LTS JDK and a matching Spring Boot release, then verify against the current support timelines before locking versions. The specific numbers change; the discipline of pinning and checking doesn't.