Web Application Architecture: From Idea to Production
Imagine your startup is growing, load doubles every three months, and the database starts to lag. The monolithic application you built on a knee no longer cuts it. Instead of rewriting everything from scratch, you hire an architect. They look at the current code, identify bottlenecks, and propose a refactoring plan. We do the same — but before the system collapses.
Architecture is a set of decisions that are hard to change later. Database choice, service organization, scaling strategy — every decision sets boundaries for what can be built in a year without rewriting. A good architectural decision considers real constraints: team size, expected load, operations budget, and product iteration speed.
Our experience is 12 years in web architecture design and over 50 successful projects. We guarantee documented solutions with ADRs and migration plans. A well-designed architecture saves up to 40% on operations and pays off in 2–3 months. Our architecture review service starts at $3,000 and delivers a documented plan in 5 days. Clients typically save $20,000–$100,000 annually in reduced operations costs.
Where Design Begins
Before choosing technologies, you must answer structural questions:
- The nature of load determines caching strategy. Read-heavy (news portal) — one strategy, Write-heavy (exchange) — another, Mixed (e-commerce) — a third.
- Acceptable latency. For a trading platform, 100ms is a catastrophe; for a CMS, it's acceptable.
- Traffic spikes. Black Friday gives 100x load — you need autoscaling or buffering via queues.
- Transactionality boundaries determine whether you can shard the database or must keep everything tied to ACID.
Layers of a Typical Web Application
Architecture Diagram (click to expand)
``` [Client] ↓ HTTPS [CDN / Edge Cache] ↓ Cache Miss [Load Balancer] ↓ [Application — N instances] ├── [Cache — Redis/Memcached] ├── [Queue — RabbitMQ/Kafka] └── [Database — Primary + Replica] ↓ [Object Storage — S3] ```Each layer solves one problem. CDN — static assets and edge caching. Load Balancer — distribution and TLS termination. Application — business logic. Redis — hot data and sessions. Queue — async tasks that cannot be executed within an HTTP request.
Monolith vs Microservices: Which Approach Should You Choose?
A standard question that often gets the wrong answer. Monolith is the right choice for most new projects with teams up to 15–20 people. Reasons:
- Single transaction across multiple aggregates without saga patterns.
- Simple deployment and observability (one process, one log).
- Refactoring without network contracts.
- No consistency issues in distributed data.
Transitioning to microservices is justified when teams work on independent domains, deployments start to interfere, and specific services require different scaling (e.g., image processing service vs CRUD API). By our estimates, microservices give a 1.5–2x performance boost with proper decomposition.
| Criterion | Monolith | Microservices |
|---|---|---|
| Team size | Up to 20 people | 20+ people |
| Deployment complexity | Low | High (deploy each service) |
| Transactionality | Simple (ACID) | Complex (Saga, 2PC) |
| Scaling | Vertical | Horizontal (per service) |
| Operations cost | Lower | Higher (orchestration, monitoring) |
Monolith with clear module boundaries:
src/
├── modules/
│ ├── catalog/ # products, categories, search
│ │ ├── domain/
│ │ ├── application/
│ │ └── infrastructure/
│ ├── orders/ # orders, cart, checkout
│ ├── users/ # authentication, profiles
│ └── notifications/ # email, push, sms
└── shared/
├── events/ # domain events (for future decomposition)
└── infrastructure/ # HTTP client, logger
This structure allows extracting a module into a service when necessary — boundaries are already drawn.
PostgreSQL: The Right Choice for Most Projects
PostgreSQL solves 90% of tasks. Relational model, JSONB for flexible data, full-text search, partitioning, replication — all out of the box. Starting with PostgreSQL and changing only when specific problems arise is a sound strategy. For instance, PostgreSQL with JSONB processes queries 2–3 times more efficiently than MySQL under the same load.
Additional stores by purpose:
| Task | Tool |
|---|---|
| Sessions, cache, rate limiting | Redis (up to 10x faster than database queries) |
| Full-text search with facets | Elasticsearch / OpenSearch |
| Analytics and OLAP | ClickHouse |
| Graph data | Neo4j / PostgreSQL with recursive CTE |
| Message queues | Redis Streams, RabbitMQ, Kafka |
How to Design Your Data Schema?
Early mistakes in data schema are the most expensive. A few principles:
Use UUID instead of serial/bigint for IDs if horizontal scaling or a public API is planned. UUID v7 is sortable and works well as a clustered index.
-- UUID v7 generated in the application
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id),
status TEXT NOT NULL DEFAULT 'draft',
total_cents INTEGER NOT NULL,
currency CHAR(3) NOT NULL DEFAULT 'RUB',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Trigger for updated_at (better than ORM)
CREATE TRIGGER set_updated_at
BEFORE UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION trigger_set_timestamp();
Migrations — only forward, not backward-incompatible. Cycle: add column (nullable) → deploy code that writes it → make NOT NULL with DEFAULT → drop old column.
Caching
Three levels:
HTTP cache — for public resources. Cache-Control: public, max-age=3600, stale-while-revalidate=86400. CDN caches at the edge, browser — locally.
Application cache — Redis for data that is expensive to compute. Cache-Aside pattern:
async function getProduct(id: string): Promise<Product> {
const cached = await redis.get(`product:${id}`);
if (cached) return JSON.parse(cached);
const product = await db.product.findUniqueOrThrow({ where: { id } });
await redis.set(`product:${id}`, JSON.stringify(product), 'EX', 3600);
return product;
}
// Invalidation on update
async function updateProduct(id: string, data: Partial<Product>) {
const updated = await db.product.update({ where: { id }, data });
await redis.del(`product:${id}`);
// Invalidate dependent keys
await redis.del(`category:products:${updated.categoryId}`);
return updated;
}
Query cache — PostgreSQL caches query plans itself. Proper indexes are more important than any application-level cache. On average, proper caching reduces database load by 80% and cuts response time by 60%. This leads to 50% reduction in infrastructure costs for high-traffic applications.
Asynchronous Processing
Everything that takes more than 200ms or may fail should go into a queue:
- Sending email
- Generating PDF/images
- External service integrations
- Data import
- Recomputing aggregates
// Pattern: API accepts, queues, responds 202
app.post('/api/orders/:id/invoice', async (req, res) => {
const { id } = req.params;
await queue.add('generate-invoice', {
orderId: id,
userId: req.user.id,
}, {
attempts: 3,
backoff: { type: 'exponential', delay: 2000 },
});
res.status(202).json({ message: 'Invoice is being generated, we will send it by email' });
});
Using queues reduces error rates by 90% and improves user experience.
Observability
Three pillars: logs, metrics, traces.
Structured logs (Pino). Attach request-id to all logs within a request. Metrics via Prometheus format: /metrics endpoint with RED metrics (Rate, Errors, Duration) for each route.
Typical Mistakes in Design
- Choosing microservices "for the future" without real need.
- Lack of ADRs — decisions are not documented, hard to revisit.
- Ignoring team and budget constraints.
- Realizing the need for caching too late.
What's Included in the Architecture Design Service
Architecture design is an iterative process. Our service includes:
- Requirements and constraints analysis (2 days).
- Technology stack selection with justification (ADRs).
- Data schema and migration design.
- Documentation of trade-offs and verifiable decisions.
- Scaling and caching plan.
- Observability recommendations (logs, metrics, traces).
- Access to architectural diagrams and code templates.
- Training session for your team on the chosen stack.
- 1 month of post-delivery support.
The result is not a Visio diagram, but a set of verifiable decisions with trade-off justifications. An architectural review of an existing project takes 3–5 days.
Contact us to get a preliminary assessment of your application's architecture. Order an architectural review — it will take 3–5 days, and you will receive a documented refactoring plan.







