Web Technologies

Chapter 2
Web Architecture and Engineering Principles

Bachelors Program in AI & ML
Web Technologies   •   Bachelor

Web Architecture and Engineering Principles

Introduction

Web applications are engineered systems rather than collections of web pages. They combine user interfaces, application logic, data management, communication protocols, security controls, deployment infrastructure, and operational practices. Web architecture describes how these elements are organised and how they interact. A good architecture supports functional requirements while also addressing quality attributes such as performance, scalability, availability, security, maintainability, observability, and cost.

For AI and machine learning students, architectural understanding is especially important. A predictive model may be accurate in a notebook but difficult to serve reliably to thousands of users. Model inference, feature retrieval, authentication, data storage, monitoring, and asynchronous processing must be integrated into a coherent web system. Architectural decisions therefore influence both software quality and the practical value of intelligent applications.

This chapter examines layered, three-tier, Model–View–Controller (MVC), component-based, monolithic, microservice, serverless, and event-driven architectures. These are not mutually exclusive categories. For example, a system may be a modular monolith internally, use MVC at its presentation boundary, employ components in its user interface, and process selected workloads through events. Architecture is best understood as a set of deliberate design decisions rather than a single fashionable pattern.

Learning Objectives

By the end of this chapter, students should be able to:

1. Explain the purpose of web architecture and distinguish architecture from implementation details.

2. Describe layered, three-tier, MVC, and component-based structures.

3. Compare monolithic, microservice, serverless, and event-driven systems.

4. Evaluate architectural choices using scalability, maintainability, reliability, security, and cost.

5. Select an appropriate architecture for a web or AI-enabled application.

6. Identify governance, ethical, and operational risks in modern web systems.

Architectural Foundations

An architecture defines major computational responsibilities, communication paths, data ownership, deployment boundaries, and constraints. It should be derived from requirements rather than selected solely because a technology is popular.

Functional and quality requirements

Functional requirements describe what a system does: registering users, searching products, processing payments, or generating a prediction. Quality requirements describe how well it performs these functions. Important quality attributes include:

  • Performance: response time, throughput, and resource efficiency.
  • Scalability: ability to handle increased workload by adding resources or improving organisation.
  • Availability: the proportion of time a service is operational and accessible.
  • Reliability: ability to perform correctly over time and recover from faults.
  • Maintainability: ease of understanding, modifying, testing, and deploying the system.
  • Security: protection of confidentiality, integrity, and availability.
  • Observability: ability to infer internal state from logs, metrics, and traces.
  • Cost efficiency: achieving required outcomes within financial and operational limits.

These attributes can conflict. Strong consistency may increase latency; independent deployment may increase operational complexity; extensive logging may improve diagnosis but increase storage costs. Architectural evaluation is therefore a trade-off analysis.

Coupling and cohesion

Coupling is the degree to which one module depends on another. Low coupling makes changes safer because a modification has fewer unintended effects. Cohesion is the degree to which the responsibilities within a module belong together. High cohesion generally improves comprehension and testing.

A useful design principle is to keep related responsibilities together while limiting dependencies across boundaries. Interfaces, contracts, domain events, and dependency inversion can reduce coupling. However, excessive decomposition can create many network calls and operational dependencies. The objective is not minimum coupling at any cost, but appropriate coupling.

Synchronous and asynchronous communication

In synchronous communication, a caller waits for a response, commonly through HTTP request–response interaction. It is easy to understand and suitable for operations requiring immediate feedback. In asynchronous communication, a producer submits work or publishes an event without waiting for the complete operation. Queues and event brokers support delayed processing, workload smoothing, and resilience, but introduce concerns such as duplicate delivery, ordering, retries, and eventual consistency.

Layered and Three-Tier Architecture

Layered architecture organises software into levels, with each layer exposing services to the layer above and depending primarily on the layer below. A common web arrangement is:

1. Presentation layer: user interface, HTTP controllers, input formatting, and accessibility.

2. Application or service layer: use-case coordination, authorization decisions, and transaction orchestration.

3. Domain layer: business rules and domain concepts.

4. Infrastructure or data-access layer: databases, external services, files, messaging, and technical adapters.

The strict form of the layered principle permits a layer to communicate only with adjacent layers. A relaxed form allows controlled communication with lower layers. Strict layering improves replaceability and reasoning, but may produce pass-through code when every request travels through many layers.

The three-tier architecture is a widely used deployment-oriented interpretation:

  • Presentation tier: browser or mobile client and web server responsibilities.
  • Application tier: business logic and APIs.
  • Data tier: databases and persistent storage.

The tiers may be deployed on separate machines or containers, although physical separation is not required. Three-tier design encourages separation of concerns and allows some independent scaling. For example, application servers may be replicated while the database uses indexing, replication, or caching. It does not automatically guarantee scalability: a database or poorly designed shared session store can remain a bottleneck.

A request might follow this path: a browser submits an order; the presentation tier validates its format; the application tier checks inventory and payment rules; the data tier retrieves and updates records; and the result is returned as HTML or JSON. Each boundary should have a clear contract and should validate untrusted input.

Model–View–Controller Architecture

MVC separates an interactive application into three conceptual roles:

  • Model: domain data and business rules.
  • View: representation presented to the user, such as HTML or a user-interface screen.
  • Controller: receives input, selects an operation, coordinates the model, and chooses a response.

A browser request can be routed to a controller, which invokes a model or service and supplies the result to a view. In modern API systems, the view may be a JSON representation consumed by a separate frontend rather than a server-rendered page.

MVC reduces the temptation to place all code in a single request handler. Nevertheless, an MVC framework does not ensure good architecture. Controllers can become “fat controllers” if they contain validation, business rules, persistence, and external-service calls. A stronger design keeps controllers thin and places use-case logic in application services or domain objects. Data-transfer objects can separate external representations from internal domain models.

MVC is particularly useful for conventional web applications with request-driven interactions. It is less a complete deployment architecture than an application-structuring pattern and can coexist with layered or three-tier designs.

Component-Based Architecture

Component-based architecture divides a system into replaceable units with explicit interfaces. A component may be a user-interface element, domain module, library, service, or deployable package. Components should encapsulate implementation details and expose stable contracts.

In frontend development, components such as navigation bars, forms, tables, and prediction-result panels can be composed into larger interfaces. Component properties, events, and state-management rules define how they interact. Reusable components improve consistency and reduce duplicated code, but excessive fragmentation can make control flow difficult to follow.

At system level, component boundaries should reflect stable responsibilities. A payment component, for example, should expose operations such as authorize and refund without forcing the rest of the system to understand its internal provider-specific code. Contract tests can verify that components continue to meet expected behaviour.

Useful component principles include single responsibility, explicit dependencies, information hiding, substitutability, and versioned interfaces. Components should be independently testable, but independence must be balanced against the cost of coordination.

Monolithic Architecture

A monolithic application is developed and commonly deployed as one principal unit. Monoliths can still be internally modular, layered, testable, and well designed. “Monolithic” primarily describes the deployment boundary, not necessarily poor code quality.

Strengths

A monolith is often simpler to develop and operate. Local function calls are faster and easier to debug than network calls. Transactions across modules may be straightforward, and deployment requires fewer infrastructure components. This makes a modular monolith a strong starting point for many small teams and early products.

Limitations

As the system grows, build and deployment times may increase. A small change may require redeploying the whole application, and one faulty module can affect the entire process. Independent scaling is limited: a computationally intensive recommendation feature may require scaling the whole application. Shared code and database structures can also create coupling.

A modular monolith mitigates these problems by enforcing boundaries inside a single deployment. Modules should own their logic, minimise direct access to one another’s data, and communicate through explicit interfaces.

Microservice Architecture

A microservice system consists of relatively small, independently deployable services organised around business capabilities. Each service typically owns a focused responsibility and communicates through APIs or messages. A service may own its data, although the exact database-per-service rule depends on consistency and operational requirements.

Benefits

Microservices can support independent deployment, selective scaling, technology diversity, and team autonomy. An inference service can use specialised hardware or a different runtime from the account service. Fault isolation and separate release cycles may improve organisational agility.

Costs and risks

Microservices transform local complexity into distributed complexity. Network calls can fail, be delayed, or return partial results. Debugging requires correlation identifiers, centralised logs, metrics, and distributed tracing. Data consistency becomes more difficult when a business operation spans services. Deployment, service discovery, secrets management, compatibility, and monitoring also require mature practices.

Microservices are not automatically more scalable or maintainable. They are appropriate when independent scaling, team boundaries, deployment autonomy, or domain separation justify their costs. A premature migration can slow a small team and create a distributed monolith in which services must always be released together.

Distributed data and consistency

A single database transaction can provide atomicity across changes within one database. Across multiple services, designers may use a saga: a sequence of local transactions with compensating actions if a later step fails. Sagas improve autonomy but require explicit handling of intermediate states. For example, an order may be created, payment authorised, and stock reserved; if stock reservation fails, payment may need to be voided.

Serverless Architecture

Serverless computing abstracts much of server provisioning and operational management. In Function as a Service (FaaS), code is executed in response to HTTP requests, schedules, queues, or events. Cloud platforms typically allocate resources for invocation and charge according to usage, subject to provider-specific pricing.

Serverless can reduce infrastructure administration, scale automatically for variable workloads, and accelerate delivery. It is useful for image processing, scheduled tasks, webhook handlers, and intermittent AI inference. However, execution limits, platform coupling, cold-start latency, concurrency limits, ephemeral local storage, and difficult local debugging must be considered. A serverless system still requires databases, identity controls, networking, monitoring, and secure configuration; “serverless” does not mean “without servers.”

Long-running or stateful workloads may be better served by containers or managed services. Model inference also requires attention to model loading time, memory size, accelerator availability, and version management.

Event-Driven Architecture

An event-driven architecture uses events to communicate that something has happened, such as OrderPlaced, ImageUploaded, or PaymentConfirmed. Producers publish events to a broker or event stream, and consumers react independently. Events differ from commands: a command requests an action, whereas an event records a fact.

Event-driven systems support loose temporal coupling, asynchronous processing, auditability, and fan-out. A single order event might be consumed by billing, inventory, notification, and analytics components. They also introduce important engineering obligations:

  • At-least-once delivery: consumers may receive duplicates and should be idempotent.
  • Ordering: ordering may be guaranteed only within a partition or key.
  • Retries and dead-letter handling: failures need controlled reprocessing.
  • Schema evolution: event formats must remain compatible across versions.
  • Eventual consistency: different read models may update at different times.
  • Observability: message identifiers and causation links are essential.

Event sourcing, in which state is reconstructed from an append-only event history, is a specialised technique rather than a requirement of event-driven design. It can provide an audit trail but increases storage, replay, and schema-management complexity.

Evaluating Architectural Alternatives

Architecture should be evaluated against explicit criteria. A decision matrix can compare alternatives using weighted requirements. If criterion scores are assigned on a common scale and weights sum to 1, a simple weighted score is:

\[

S=\sum_{i=1}^{n} w_i r_i

\]

where \(S\) is the total score, \(w_i\) is the importance weight for criterion \(i\), \(r_i\) is the alternative’s score for that criterion, and \(n\) is the number of criteria. This is a decision aid, not an objective law. Scores are judgment-based, and sensitivity analysis should test whether small changes in weights alter the decision.

For example, suppose a team assigns scalability weight 0.30, maintainability 0.30, operational simplicity 0.25, and cost 0.15. A modular monolith scores 3, 5, 5, and 5 respectively on a five-point scale. Its score is:

\[

0.30(3)+0.30(5)+0.25(5)+0.15(5)=4.4.

\]

A microservice alternative scoring 5, 3, 2, and 3 gives:

\[

0.30(5)+0.30(3)+0.25(2)+0.15(3)=3.5.

\]

Under these assumptions, the modular monolith is preferable despite lower scalability because maintainability and operational simplicity have substantial weight. If future requirements increase independent scaling needs, the weights and decision should be revisited.

Other useful evaluation questions include:

  • Can the system meet expected peak load and growth?
  • Which components must scale independently?
  • What happens when a dependency fails?
  • How are data ownership and consistency managed?
  • Can changes be tested and deployed safely?
  • Can operators detect and diagnose incidents?
  • What are the direct and indirect costs?
  • Does the architecture support accessibility, privacy, and regulatory obligations?

A Practical Architectural Process

A disciplined process normally begins with requirements and constraints. Designers identify users, workloads, data sensitivity, integrations, compliance obligations, and team capabilities. They then define major responsibilities and boundaries, select communication styles, and document important decisions.

Architecture decision records (ADRs) are concise documents that state the context, decision, alternatives, and consequences. Diagrams should show both logical structure and deployment relationships. Interfaces should be specified using contracts, examples, validation rules, authentication requirements, error formats, and compatibility policies.

Deployment should favour automation through version control, repeatable builds, infrastructure as code where appropriate, automated testing, and controlled release strategies. Blue–green and canary deployments can reduce release risk, but require reliable health checks and rollback procedures.

Security should be designed in rather than added later. Core practices include strong authentication, least privilege, secure secret storage, input validation, output encoding, protection against injection and cross-site request forgery, transport encryption, dependency updates, rate limiting, and audit logging. Threat modelling helps identify misuse cases before implementation.

Illustrative Case: An AI-Assisted Agricultural Advisory Platform

Background

This fictional case concerns a platform that allows farmers to submit crop images and receive disease-risk guidance. The platform also provides weather-based alerts and aggregates anonymised information for agricultural researchers.

Problem

The first version is a single web application. Image uploads block the request while a machine-learning model performs inference. During seasonal peaks, response times become unacceptable. Model updates risk disrupting account and payment functions, and researchers require a consistent data feed without querying operational tables directly.

Analysis

The system has different workload characteristics. Authentication and user profile operations are interactive and transaction-oriented. Image analysis is computationally expensive and can tolerate asynchronous processing. Alert generation is periodic and event-oriented. The model requires independent versioning and monitoring. Farmers also need an explanation of the result and an indication that the prediction is advisory rather than a guaranteed diagnosis.

Approach

The team first reorganises the application as a modular monolith. User, advisory, billing, and administration modules have explicit interfaces. Image upload returns a job identifier rather than waiting for analysis. An object store holds the image, and an event such as ImageSubmitted is published. A model-inference worker consumes the event, retrieves the image, records model version and confidence information, and emits PredictionCompleted. The web client polls or receives a notification about completion.

As usage grows, the inference worker is deployed independently because it needs different scaling and hardware. The main application remains a modular monolith. A separate analytics consumer builds a reporting dataset from approved events. Failed messages are retried and eventually placed in a dead-letter queue. Consumers use image and event identifiers to avoid processing the same submission twice.

Privacy controls restrict access to images, define retention periods, and separate personally identifiable information from research data. Model monitoring checks for changes in input quality and prediction distributions. Human agronomists review uncertain or high-impact recommendations.

Outcome

Interactive requests become independent of inference duration, and inference capacity can scale without replicating the entire application. The system remains simpler than a fully decomposed microservice platform. Its design also makes uncertainty, model provenance, data governance, and human oversight visible parts of the architecture.

Learning points

The case demonstrates that architecture should follow workload and risk boundaries. Asynchronous events are useful where immediate completion is unnecessary, while a modular monolith can remain appropriate for closely related transactional functions. AI introduces additional requirements: model versioning, data lineage, monitoring, explainability, privacy, and mechanisms for human review.

Challenges, Ethics, and Governance

Architecture can create social and legal consequences. Personal data should be collected for legitimate purposes, minimised, protected, and retained only as long as justified. Access decisions should be auditable. AI services must address biased data, uncertain outputs, inappropriate automation, and the possibility that users interpret predictions as facts.

Availability and accessibility are also ethical concerns. A system that excludes users with disabilities or unreliable connectivity is not professionally complete. WCAG-informed interface practices, keyboard support, sufficient contrast, alternative text, and clear error messages should be treated as design requirements.

Third-party services introduce supply-chain and jurisdiction risks. Organisations should assess vendor dependence, data-processing terms, outage behaviour, portability, and exit strategies. Open-source dependencies require licence and vulnerability management. Logging must support accountability without unnecessarily exposing sensitive information.

Contemporary Developments and Best Practices

Modern web engineering increasingly combines managed cloud services, containers, edge delivery, API gateways, event streams, and platform engineering. These tools can improve delivery but do not replace architectural reasoning. AI-assisted coding and automated deployment should be governed through code review, testing, provenance, and secure development practices.

Best practices include:

1. Start with requirements, constraints, and measurable quality attributes.

2. Prefer the simplest architecture that satisfies current and near-term needs.

3. Enforce modular boundaries before splitting into distributed services.

4. Design APIs and events as versioned contracts.

5. Make retries, timeouts, idempotency, and failure states explicit.

6. Automate testing, deployment, security checks, and rollback.

7. Build observability into every important interaction.

8. Protect data through minimisation, encryption, access control, and retention policies.

9. Record architectural decisions and revisit them when assumptions change.

10. For AI features, track data provenance, model versions, uncertainty, drift, and human escalation paths.

Chapter Summary

Web architecture organises responsibilities, communication, data, and deployment boundaries. Layered and three-tier structures separate presentation, application, domain, and data concerns. MVC structures request-driven applications through models, views, and controllers, while component-based design promotes encapsulation and reuse.

Monoliths offer simplicity and are often appropriate when a team or product is small. Microservices provide independent deployment and scaling but introduce distributed-systems complexity. Serverless platforms reduce infrastructure management for suitable workloads, while event-driven systems support asynchronous processing and loose coupling at the cost of delivery, ordering, consistency, and observability challenges.

Architecture must be evaluated against requirements rather than trends. Scalability, maintainability, reliability, security, cost, team capability, and governance should be considered together. A modular monolith can be a deliberate and highly professional choice, and systems can combine multiple architectural styles. AI-enabled web systems additionally require model governance, data protection, monitoring, explainability, and human oversight.

Key Terms

Architecture: Organisation of a system’s responsibilities, interactions, data, and deployment boundaries.

Layered architecture: Structure in which software is divided into responsibility-based levels.

Three-tier architecture: Separation into presentation, application, and data tiers.

MVC: Model–View–Controller pattern for separating domain data, presentation, and input coordination.

Component: Encapsulated unit with a defined interface and responsibility.

Coupling: Degree of dependency between modules or components.

Cohesion: Degree to which responsibilities within a module belong together.

Monolith: Application deployed as one principal unit.

Modular monolith: Single deployment containing strongly separated internal modules.

Microservice: Independently deployable service organised around a focused capability.

Serverless: Cloud execution model that abstracts much server provisioning and management.

Function as a Service: Event- or request-triggered execution of functions on managed infrastructure.

Event: Record that a significant fact or state change has occurred.

Event broker: Infrastructure that routes, stores, and delivers messages or events.

Idempotency: Property whereby repeated processing has the same intended effect as one processing.

Eventual consistency: State in which replicas may temporarily differ before converging.

Observability: Ability to understand internal system behaviour using outputs such as logs, metrics, and traces.

Saga: Sequence of local transactions coordinated with compensating actions.

Architecture decision record: Document capturing the context, decision, alternatives, and consequences of an architectural choice.

Review Questions

Short Answer Questions

1. What is the difference between coupling and cohesion?

2. Identify the three tiers in a conventional three-tier architecture.

3. Why can a modular monolith be preferable to microservices for a small team?

4. What is an event in an event-driven architecture?

5. State two challenges associated with serverless computing.

Long Answer Questions

1. Explain layered architecture and discuss its advantages and limitations.

2. Compare MVC and component-based architecture, including how they can coexist.

3. Evaluate the benefits and costs of microservice architecture.

4. Explain how asynchronous processing improves the agricultural advisory platform in the case study.

5. Discuss security, privacy, and AI-governance requirements in web architecture.

Analytical / Application Questions

1. A university portal has stable enrolment transactions but highly variable demand for document conversion. Recommend an architecture and justify where synchronous and asynchronous processing should be used.

2. A team proposes splitting a new application into twelve microservices before releasing its first version. Analyse the risks and propose a more suitable evolution strategy.

3. Design an architectural decision matrix for an AI image-search system. Select at least four criteria, assign weights, compare two alternatives, and explain the sensitivity of your decision.

Multiple Choice Questions with Answers

Question 1

Which statement best describes a modular monolith?

A. A system with no internal separation of responsibilities

B. A single deployment containing explicitly separated internal modules

C. A collection of independently deployed services

D. A system that runs only as cloud functions

Correct Answer: B. A single deployment containing explicitly separated internal modules

Question 2

In MVC, which role normally receives user input and coordinates an operation?

A. The view

B. The database

C. The controller

D. The event broker

Correct Answer: C. The controller

Question 3

Which characteristic is most directly associated with microservices?

A. Independent deployment of focused services

B. Mandatory use of one shared database transaction

C. Absence of network communication

D. Deployment only on physical servers

Correct Answer: A. Independent deployment of focused services

Question 4

Why should event consumers commonly be idempotent?

A. Events are always delivered in exactly-once order

B. Duplicate delivery can occur in many messaging systems

C. Idempotency eliminates the need for monitoring

D. It guarantees that all data is strongly consistent

Correct Answer: B. Duplicate delivery can occur in many messaging systems

Question 5

Which is a common serverless limitation?

A. It cannot respond to events

B. It always requires manually managed physical servers

C. Execution limits and cold-start latency may affect applications

D. It prevents automatic scaling

Correct Answer: C. Execution limits and cold-start latency may affect applications

Question 6

In the weighted decision example, what score was calculated for the modular monolith?

A. 2.5

B. 3.5

C. 4.0

D. 4.4

Correct Answer: D. 4.4

Question 7

Which quality attribute concerns the ability to understand internal behaviour through logs, metrics, and traces?

A. Observability

B. Portability

C. Cohesion

D. Compression

Correct Answer: A. Observability

Question 8

What is the primary purpose of a saga in a distributed system?

A. To replace all monitoring tools

B. To coordinate local transactions and compensating actions

C. To guarantee zero network failures

D. To render user-interface components

Correct Answer: B. To coordinate local transactions and compensating actions

Question 9

Which architectural decision best separates expensive image inference from interactive web requests?

A. Perform inference synchronously in every page-rendering request

B. Remove authentication from the application

C. Submit an asynchronous job processed by an inference worker

D. Store all images in browser cookies

Correct Answer: C. Submit an asynchronous job processed by an inference worker

Question 10

Which practice is especially important for AI-enabled web systems?

A. Ignoring model versions after deployment

B. Tracking model provenance, uncertainty, and drift

C. Using one database table for every purpose

D. Disabling human review for uncertain outputs

Correct Answer: B. Tracking model provenance, uncertainty, and drift

Web Technologies
Chapter 2 of 14