Chapter 1
Foundations of Web Security and Performance
Bachelors Program in Full Stack Development
Web Security & Performance Optimization
•
Bachelor
Foundations of Web Security and Performance
Introduction and Context
Modern web applications are distributed systems. A user interaction may involve a browser, a local operating system, recursive and authoritative DNS services, an edge network, a load balancer, application services, caches, databases, identity providers, and third-party APIs. Security and performance therefore cannot be treated as separate afterthoughts. A security control may add computation, network round trips, or serialization overhead; an optimization may enlarge the attack surface or weaken confidentiality.
This chapter establishes a systems-level foundation for analysing those interactions. It explains the web request path, HTTP and HTTPS, DNS, browser and server responsibilities, distributed-system properties, core security principles, attack surfaces, and performance metrics. It also introduces methods for reasoning about trade-offs rather than memorising isolated technologies.
Learning Objectives
By the end of this chapter, you should be able to:
Explain how browsers, DNS, networks, servers, caches, and databases cooperate to deliver a web resource.
Distinguish HTTP, TLS, HTTPS, TCP, and QUIC, including the different establishment sequences of TCP-based and QUIC-based connections.
Apply confidentiality, integrity, availability, least privilege, defense in depth, and attack-surface analysis to a web system.
Interpret latency, throughput, scalability, reliability, availability, and tail-performance measurements.
Analyse security–performance trade-offs and propose proportionate controls.
Evaluate an architectural scenario using a structured security and performance method.
1. The Web as a Layered, Distributed System
A web application is best understood through layers, although real products do not always preserve perfectly separate boundaries.
Presentation layer: the browser renders HTML, CSS, images, and scripts and handles user interaction.
Application layer: server-side code applies business rules, authentication, authorization, validation, and response generation.
Data layer: databases, object stores, search indexes, and queues persist or process information.
Network and transport layers: IP moves packets between hosts; TCP or QUIC provides transport semantics.
Security layer: TLS protects data in transit and authenticates endpoints.
Operational layer: monitoring, logging, deployment, configuration, and incident response sustain the service.
Layering supports reasoning: a browser may enforce a same-origin policy while TLS protects a connection and an application checks whether a user may access a particular record. These controls address different threats and are not substitutes for one another.
A Corrected Request Flow
DNS is a naming and discovery mechanism. It resolves a hostname to an address or service information; the subsequent HTTP request is sent to the selected endpoint. DNS is not an intermediary through which the HTTP request passes. Similarly, a cache is normally consulted by an edge or application component according to an explicit caching design, and the application controls database access rather than a database independently contacting the cache.
Web request architecture showing DNS resolution separately from the HTTP request path
Figure: Web request architecture showing DNS resolution separately from the HTTP request path
Figure: DNS resolution is separate from the HTTP request path; the application may consult a cache and database as part of request processing.
A typical sequence is:
The browser parses a URL and checks relevant local caches, service workers, and connection pools.
If needed, it resolves the hostname through a configured DNS resolver.
It establishes or reuses a secure transport connection to the selected endpoint.
It sends an HTTP request containing a method, target, headers, and possibly a body.
The edge layer may enforce rate limits, routing, and access policies.
The application authenticates the request, authorizes the operation, validates input, and may read a cache or database.
The response returns through the appropriate layers and is interpreted by the browser.
This is a logical model, not a guarantee that every deployment has each component.
2. DNS, HTTP, HTTPS, TCP, and QUIC
DNS
The Domain Name System maps names such as example.org to resource records. An iterative or recursive resolution process can involve a stub resolver, recursive resolver, root servers, top-level-domain servers, and authoritative servers. Caching reduces lookup latency and traffic, but cached records remain valid only for their time-to-live (TTL). DNSSEC can provide authenticity for DNS data through digitally signed records; it does not encrypt ordinary DNS queries. Encrypted DNS transports, such as DNS over HTTPS or DNS over TLS, protect the query channel from some observers but do not by themselves prove that the final web application is trustworthy.
HTTP
HTTP is an application protocol with methods, status codes, headers, and representations. HTTP semantics are largely independent of the transport. GET is intended for retrieval and is generally safe; POST commonly requests processing that may change state; PUT and DELETE have defined replacement and deletion semantics, but safe implementation still requires authorization and validation. Idempotency is a property of repeated intended effects, not a permission to omit authentication or transaction controls.
HTTP/1.1 commonly uses one request at a time per connection in a sequence, although multiple connections may be opened. HTTP/2 multiplexes streams over one connection and compresses headers. HTTP/3 uses HTTP semantics over QUIC rather than TCP. Multiplexing can reduce connection overhead, but contention, prioritization mistakes, or excessive concurrent work can still harm performance.
TLS and HTTPS
HTTPS is HTTP carried through TLS. TLS provides confidentiality against passive network observation, integrity against modification, and endpoint authentication when certificate validation succeeds. It does not make an application logic flaw safe, prevent a malicious authorized user from misusing data, or guarantee availability.
For a TCP-based deployment, a simplified sequence is:
Resolve the hostname.
Establish a TCP connection using the transport handshake.
Perform the TLS handshake, negotiating cryptographic parameters and authenticating the server certificate.
Exchange encrypted HTTP messages.
The exact sequence can include session resumption, early data, proxies, and connection reuse. Early data requires care because replay risks may exist for operations that change state.
QUIC is a secure transport built over UDP. TLS 1.3 supplies the cryptographic handshake inside QUIC; it is not accurate to describe QUIC as completing a generic TCP-style handshake and then performing a wholly separate TLS handshake. QUIC packets carry TLS handshake information, and connection establishment integrates transport and cryptographic negotiation. QUIC supports stream multiplexing and connection migration, while applications must still consider authentication, authorization, and resource exhaustion.
Browser Security Boundaries
Browsers implement several important controls:
Same-origin policy: scripts are restricted from freely reading data across origins, where an origin is determined by scheme, host, and port.
CORS: a server can selectively permit controlled cross-origin browser requests; it is not a server-side access-control substitute.
Content Security Policy: a response can restrict script, style, frame, and resource sources, reducing some injection consequences.
Cookie attributes:Secure limits transmission to HTTPS, HttpOnly limits script access, and SameSite controls cross-site sending patterns.
Mixed-content protection: browsers restrict insecure subresources on secure pages.
These mechanisms are defense layers. A server must independently authenticate and authorize every sensitive operation because non-browser clients can send requests without browser restrictions.
3. Core Security Models and Principles
The CIA Triad
The CIA triad describes three security objectives:
Integrity: preventing unauthorized or undetected alteration.
Availability: ensuring an authorized service remains usable within agreed conditions.
A control can support more than one objective. Encryption primarily supports confidentiality and integrity in transit; redundancy primarily supports availability; audit logs support integrity and accountability but must themselves be protected.
Security analysis should identify assets, actors, trust boundaries, threats, controls, and residual risk. A useful threat statement specifies an actor, capability, target, action, and consequence rather than merely naming a vulnerability.
Least Privilege
Least privilege grants each identity only the permissions required for its task, for only as long as necessary. A web process should not ordinarily possess unrestricted administrative database rights. Separate service accounts, narrowly scoped tokens, short-lived credentials, and just-in-time elevation reduce blast radius. Least privilege applies to users, services, browser scripts, deployment pipelines, and administrators.
Defense in Depth
Defense in depth uses independent or partially independent controls so that failure of one control does not expose the whole system. For example, parameterized queries reduce injection risk, input validation rejects malformed data, a restricted database account limits consequences, network segmentation limits reachability, and monitoring supports detection. Redundant controls are not automatically effective: several controls depending on the same unverified assumption may create an illusion of depth.
Attack Surface
An attack surface is the set of reachable interfaces, exposed data, privileges, dependencies, and execution paths that an adversary might influence. It includes HTTP endpoints, administrative panels, upload handlers, open ports, DNS records, browser scripts, CI/CD systems, third-party packages, cloud identities, and operational interfaces.
Attack-surface reduction is not simply deleting features. It involves removing unnecessary services, closing unused ports, restricting administrative access, reducing dependency privileges, validating inputs at boundaries, and separating public from internal interfaces. A smaller surface is generally easier to monitor and test, but a hidden interface is not necessarily a secure interface.
Trust Boundaries and Identity
A trust boundary is a transition where data or authority moves between parties with different assumptions. Examples include browser-to-server, public gateway-to-application, application-to-database, and organization-to-third-party API. At every boundary, establish identity where needed, validate syntax and semantics, enforce authorization, constrain resource use, and record security-relevant events without logging secrets.
Authentication answers “who or what is this?” Authorization answers “what may it do?” Confusing the two is a common architectural error. A user authenticated as Alice is not automatically authorized to retrieve every account record.
4. Performance and Distributed-System Reasoning
Latency and Throughput
Latency is elapsed time for an operation, often measured from request receipt to response completion. Throughput is completed work per unit time, such as requests per second or transactions per second. They are related but distinct: batching may improve throughput while increasing individual latency.
Here each term is a nonnegative time component, measured in milliseconds or seconds. The model assumes the components are sequential and non-overlapping; real systems can overlap DNS, connection work, and processing, so it is a diagnostic approximation rather than a universal law.
For a workload with completed requests N over elapsed time T, average throughput is:
X = N ÷ T
If 12,000 requests complete in 60 seconds, X = 12000 ÷ 60 = 200 requests per second. This does not reveal whether requests were evenly distributed or whether a few experienced very long delays.
Percentiles are therefore important. The p95 latency is the value at or below which approximately 95% of observations fall; p99 exposes tail behaviour more strongly. Averages can look healthy while a minority of users experience timeouts.
Queueing and Capacity
A useful operational relationship is Little’s Law:
N = X × R
N is the average number of items in the system, X is throughput, and R is average time in the system. Units are consistent: requests/second × seconds = requests. The law applies to a stable system over a suitable observation interval, where average arrival and departure rates are equal and the measured population boundary is clearly defined.
If an endpoint sustains 100 requests per second and average response time is 0.4 seconds, the average number of in-system requests is N = 100 × 0.4 = 40. This is not a license to increase concurrency indefinitely: as utilization approaches capacity, queueing delay can rise sharply.
Scalability
Vertical scaling increases resources on a component; horizontal scaling adds instances. Stateless application services are easier to replicate because session state is externalized or represented in securely managed tokens. Horizontal scaling does not automatically scale a database, a locking protocol, a third-party quota, or a shared cache.
Amdahl’s law illustrates a limit on speedup when a fraction of work is inherently serial:
S(p) = 1 ÷ (s + (1 − s) ÷ p)
Here s is the serial fraction, p is the number of parallel workers, and S(p) is ideal speedup relative to one worker. The formula assumes fixed workload, negligible parallelization overhead, and a clear serial/parallel partition. If s = 0.2 and p = 4, then S = 1 ÷ (0.2 + 0.8 ÷ 4) = 1 ÷ 0.4 = 2.5. The result is an ideal bound, not a performance guarantee.
Reliability and Availability
Reliability concerns the probability or ability of a system to perform correctly over time; availability concerns whether it is usable when requested. A common measurement is:
Availability = uptime ÷ (uptime + downtime)
This ratio requires a defined measurement window and a precise definition of downtime. A service with 99.9% availability over a 30-day period has approximately 0.001 × 30 × 24 × 60 = 43.2 minutes of unavailable time, ignoring the organization’s specific measurement exclusions.
Redundancy can improve availability, but correlated failures—such as a shared region, credential, deployment, or dependency—limit the benefit. Distributed systems also face partial failure: one component may be unavailable while others continue operating. Timeouts, bounded retries with jitter, circuit breakers, idempotency keys, and graceful degradation help, but retries can amplify overload if not controlled.
5. Security–Performance Trade-offs
Security and performance should be evaluated together with user and business risk.
TLS: encryption and certificate validation add computation and handshake work, but connection reuse, session resumption, modern hardware, and HTTP/2 or HTTP/3 can reduce marginal cost. Omitting TLS is not an acceptable optimization for sensitive traffic.
Authorization: checking permissions adds processing and possibly a data lookup. Caching authorization decisions may reduce latency, but stale permissions can create security exposure. Decisions should have explicit expiry and revocation strategy.
Logging: detailed logs support detection and forensics but consume CPU, storage, and network capacity. Structured, sampled, access-controlled logs are preferable to indiscriminate collection.
Caching: caching improves latency and origin capacity, yet sensitive responses require correct cache keys, isolation, expiry, and invalidation. A cache-control mistake can disclose one user’s data to another.
Input limits: maximum body size, execution time, and concurrency protect availability. Limits must be high enough for legitimate use and enforced before expensive processing.
Compression: compression saves bandwidth but can create information-leakage risks in some contexts when attacker-controlled and secret data are compressed together. It also consumes CPU.
Availability controls: replication and failover improve resilience but increase synchronization, operational complexity, and sometimes consistency costs.
A sound design makes the trade-off explicit: identify the protected asset, expected threat, performance budget, failure mode, and compensating control.
6. A Practical Analysis Method
A repeatable review can proceed as follows:
Map the request path. Identify browser, DNS resolution, transport, edge, application, cache, data stores, and external services. Mark which arrows are control flow and which are data flow.
Define assets and trust boundaries. Include personal data, credentials, payment data, tokens, availability, and intellectual property.
Enumerate interfaces. List endpoints, methods, upload paths, management interfaces, ports, identities, dependencies, and deployment systems.
Model threats. Consider spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege.
Measure a baseline. Collect request rate, error rate, p50/p95/p99 latency, resource utilization, cache hit ratio, database time, and dependency timings.
Apply controls proportionately. Prefer controls that reduce both risk and operational complexity, such as centralized policy enforcement and secure defaults.
Test under realistic load and failure. Include expired credentials, partial dependency failure, cache poisoning attempts, large inputs, and traffic spikes.
Observability should not become surveillance without governance. Collect the minimum data needed, restrict access, define retention, protect logs from alteration, and comply with applicable privacy and data-protection requirements.
7. Illustrative Case: Campus Course Platform
Background
A fictional university course platform serves lecture pages, assignments, grades, and submissions. It uses a browser client, a public gateway, replicated application services, a cache, a relational database, and an object store for submitted files.
Problem
During assessment deadlines, p95 latency rises from 350 ms to 4 seconds, submission failures increase, and a configuration error once caused a cached course page to be delivered across departments. The platform team proposes disabling authorization checks on read requests and allowing unlimited upload size to improve speed and convenience.
Analysis
The proposed changes confuse performance symptoms with security controls. The likely bottlenecks are bursty demand, database contention, file-processing work, and insufficient queue protection. Unlimited uploads create an availability and storage-exhaustion risk. Removing authorization could disclose grades or private materials. The cache incident indicates an incorrect cache key or cacheability policy, not that caching is inherently unsafe.
The team maps the path and measures each component. It separates public course metadata from user-specific grades, uses cache keys containing the course and access context where appropriate, and marks private responses non-shareable. Authorization remains in the application and is tested against the current user and course role. Uploads receive size, type, rate, and malware-scanning limits; scanning is moved to an asynchronous workflow with a clear pending state.
Database indexes are reviewed using actual query plans rather than guesswork. Connection pools and queue sizes are bounded. The gateway applies rate limits, while the application uses idempotency keys for retryable submission operations. Read replicas are considered only after consistency requirements are documented. TLS remains mandatory, and service accounts receive only the database permissions they need.
Outcome
In this illustrative design, controlled caching reduces repeated public reads, bounded asynchronous processing prevents upload work from exhausting request threads, and query improvements reduce database service time. More importantly, the team measures p95 and p99 latency separately, tests cache isolation, and monitors authorization failures and queue depth. The design accepts a small delay for malware scanning rather than treating immediate availability as the only performance objective.
Learning Points
Performance optimization must begin with measurement and a component-level hypothesis.
Authorization is not an optional latency feature; it is part of the application’s security contract.
Cache correctness includes confidentiality and isolation, not merely hit ratio.
Bounded work and graceful degradation protect both availability and security.
Architecture diagrams must distinguish DNS resolution from request forwarding and must show who controls cache and database access.
8. Contemporary Developments and Professional Practice
Cloud platforms provide managed TLS, identity, databases, content delivery, and autoscaling, but responsibility is shared: a provider may secure infrastructure while the application owner configures access policies, data exposure, secrets, and code. Infrastructure as code and automated policy checks can make secure configuration repeatable.
WebAssembly, edge computing, service meshes, and AI-assisted development introduce new execution locations and dependencies. They may reduce latency or improve productivity, but they also expand supply-chain, identity, observability, and data-governance questions. AI-generated code should undergo human review, dependency scanning, testing, threat modelling, and license and privacy assessment. Neither AI output nor a vendor security label replaces evidence.
Professionals should use current standards and advisories, maintain an asset inventory, patch according to risk, rotate credentials, test backups and recovery, and practise incident response. Security objectives, service-level objectives, data classification, and regulatory duties should be documented before optimization decisions are made.
Challenges and Limitations
No single diagram or metric captures a distributed system completely. DNS answers can change, caches can be stale, networks can reorder or lose packets, and failures can be correlated. Synthetic tests may not represent real browsers or geographic users; averages conceal tail latency; and benchmark improvements can disappear under realistic concurrency. Security controls can also fail through misconfiguration, weak operational processes, or compromised dependencies. Consequently, architecture must be continuously tested, observed, and revised.
Chapter Summary
The web is a layered distributed system in which DNS resolves names but does not carry HTTP requests. Browsers, transport protocols, TLS, gateways, applications, caches, and databases have distinct responsibilities. TCP-based HTTPS commonly establishes TCP before TLS, whereas QUIC integrates TLS 1.3 into its connection establishment. HTTPS protects communication but does not replace application authorization.
The CIA triad frames confidentiality, integrity, and availability. Least privilege limits authority, defense in depth provides independent protection, and attack-surface analysis identifies reachable interfaces and consequences. Performance analysis distinguishes latency, throughput, scalability, reliability, and availability. Latency components, throughput calculations, Little’s Law, Amdahl’s law, and percentile measurements provide useful but assumption-dependent models.
Security and performance must be designed together. Caching, compression, retries, logging, authorization, encryption, and replication each have benefits and risks. A disciplined process maps flows, identifies assets and boundaries, models threats, measures a baseline, applies controls, tests failure, and reviews residual risk.
Key Terms
DNS: A distributed naming system that maps domain names to resource records.
HTTP: An application protocol for request and response messaging on the web.
HTTPS: HTTP protected by TLS.
TLS: A cryptographic protocol providing confidentiality, integrity, and endpoint authentication when correctly validated.
TCP: A connection-oriented transport protocol with reliable, ordered byte-stream delivery.
QUIC: A UDP-based secure transport integrating TLS 1.3 and supporting multiplexed streams.
Origin: The combination of scheme, host, and port used by browser security policy.
CIA triad: Confidentiality, integrity, and availability.
Least privilege: Granting only the authority necessary for an authorized task.
Defense in depth: Using multiple, partly independent security controls.
Attack surface: Reachable interfaces, privileges, data, and execution paths exposed to potential attack.
Trust boundary: A transition between components or parties with different security assumptions.
Latency: Elapsed time required to complete an operation.
Throughput: Completed work per unit time.
Tail latency: High-percentile response time, such as p95 or p99.
Scalability: The ability to handle increased demand while maintaining required properties.
Availability: The proportion of defined service time during which a service is usable.
Cache: A store of reusable data intended to reduce origin work or retrieval time.
Idempotency: The property that repeating an operation has the same intended effect as performing it once.
Little’s Law: The stable-system relationship N = X × R between population, throughput, and response time.
Review Questions
Short Answer Questions
Why is DNS not an intermediary in the HTTP request path?
State the three elements of the CIA triad and give one web example of each.
Distinguish authentication from authorization.
What is the purpose of the HttpOnly cookie attribute?
Why are p95 and p99 latency often more informative than average latency?
Long Answer Questions
Explain the logical flow of a browser request from URL entry to database-backed response, identifying trust boundaries and security controls.
Compare TCP-based HTTPS with HTTP/3 over QUIC, including connection establishment and performance implications.
Explain how least privilege and defense in depth would be applied to an application service that accesses a database.
Discuss how caching can improve performance while creating confidentiality and consistency risks.
Evaluate the statement: “Horizontal scaling solves performance problems.” Include databases, dependencies, state, and coordination.
Analytical / Application Questions
A service processes 240 requests per second with an average response time of 0.25 seconds. Use Little’s Law to estimate the average number of requests in the system, state the assumptions, and explain why the result does not establish p99 performance.
A team wants to remove TLS session resumption and authorization checks because p95 latency is high. Construct a safer investigation and optimization plan that preserves security objectives.
Design a threat and performance review for a file-upload endpoint. Identify at least four attack-surface elements, three availability controls, two confidentiality or integrity controls, and the measurements needed to validate the design.
Multiple Choice Questions with Answers
Question 1
A browser resolves shop.example to an address and then sends an HTTPS request. Which architectural statement is most accurate?
A. The DNS resolver forwards the HTTP request to the application.
B. DNS supplies resolution information; the browser then sends the request to the selected endpoint.
C. The database receives the DNS response and chooses the HTTP server.
D. The cache must forward every DNS response before HTTP can begin.
Correct Answer: B. DNS supplies resolution information; the browser then sends the request to the selected endpoint.
Question 2
A deployment uses HTTP/3 over QUIC. Which statement best describes connection establishment?
A. QUIC first completes TCP and then starts TLS 1.3 as a separate protocol exchange.
B. QUIC cannot provide encryption because UDP has no handshake.
C. TLS 1.3 cryptographic negotiation is integrated into QUIC connection establishment.
D. HTTP/3 replaces authentication with DNSSEC.
Correct Answer: C. TLS 1.3 cryptographic negotiation is integrated into QUIC connection establishment.
Question 3
An application service handles 100 requests per second with an average time in the system of 0.4 seconds. Under stable conditions, what average in-system population follows from Little’s Law?
A. 25 requests
B. 40 requests
C. 100 requests
D. 250 requests
Correct Answer: B. 40 requests
Question 4
A cache returns one student’s grade page to another student. Which design failure is the most directly implicated?
A. The cache key or cacheability policy failed to isolate user-specific content.
B. The browser used HTTP/2 multiplexing.
C. DNS used a short TTL.
D. The database used a normalized schema.
Correct Answer: A. The cache key or cacheability policy failed to isolate user-specific content.
Question 5
A service has a serial fraction of 0.2 and otherwise ideal parallel work. Under Amdahl’s assumptions, what is the ideal speedup with four workers?
A. 1.25
B. 2.0
C. 2.5
D. 4.0
Correct Answer: C. 2.5
Question 6
Which design best demonstrates least privilege?
A. Giving every microservice the same database administrator credential.
B. Allowing a reporting service read-only access to only the required views.
C. Allowing unauthenticated access because the network is private.
D. Using a permanent administrator token for deployment and runtime traffic.
Correct Answer: B. Allowing a reporting service read-only access to only the required views.
Question 7
A team observes a good mean latency but unacceptable p99 latency during traffic bursts. Which conclusion is most defensible?
A. The mean proves all users receive acceptable service.
B. Only DNS can explain the result.
C. Tail behaviour should be investigated for queueing, contention, and overload.
D. Increasing payload size will necessarily reduce p99 latency.
Correct Answer: C. Tail behaviour should be investigated for queueing, contention, and overload.
Question 8
Which statement about browser CORS is correct?
A. CORS replaces server-side authorization for API requests.
B. CORS controls whether browser scripts may make certain cross-origin requests or read responses.
C. CORS encrypts requests between the browser and server.
D. CORS prevents non-browser clients from calling an endpoint.
Correct Answer: B. CORS controls whether browser scripts may make certain cross-origin requests or read responses.
Question 9
An application retries a timed-out payment request. Which control most directly reduces the risk of duplicate payment effects?
A. An idempotency key interpreted by the payment operation.
B. A larger image cache.
C. A shorter DNS TTL.
D. Disabling TLS session resumption.
Correct Answer: A. An idempotency key interpreted by the payment operation.
Question 10
Which proposed optimization most clearly creates a direct confidentiality risk?
A. Reusing an established TLS connection for multiple authorized requests.
B. Compressing public static assets.
C. Caching private responses under a key that omits the user or access context.
D. Adding a bounded request-body size.
Correct Answer: C. Caching private responses under a key that omits the user or access context.
Web Security & Performance Optimization
Chapter 1
of 15