The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← Back to program

← CS 220 — Web Applications, SQL and Software Engineering

Weeks 15–16

Integrated application architecture and tradeoffs

Learning objectives

  • Explain and trace the mechanisms in integrated application architecture and tradeoffs.
  • Apply the method to the worked example and changed-condition exercise.
  • Identify assumptions, failure cases and the evidence needed to justify a result.

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

Architecture allocates responsibilities across components. In a small web application, the browser presents information and captures input; the server validates requests and applies authorization; the database persists constrained records. Making the browser responsible for privileged rules exposes them to bypass. Making every operation one large server function can make changes difficult to reason about. Boundaries should follow responsibilities rather than fashionable terminology.

Caching improves performance only when stale data is acceptable under a specified policy. Public educational descriptions and private customer orders have different privacy and freshness requirements. A cache key missing the user identity can expose another account's response. Likewise, a static page export cannot replace a server application that depends on authenticated APIs and persistence. Deployment format is part of the architecture.

Evaluate alternatives using the actual workload. A single relational database and server can be more suitable than a collection of services for a modest application. Distributed components add partial failures, retries, identity propagation and observability needs. Describe when the simple design would stop meeting requirements. A readiness review should trace one request end to end, including an invalid input, a denial, a database error and a retry, then demonstrate that the resulting state remains coherent.

Worked reasoning The function illustrates a privacy-first classification, not a complete HTTP caching implementation. The route must actually attach the returned header and avoid another layer overriding it. A shared cache must never store private responses merely because the URL path is the same for all users. Test the real response headers as part of deployment validation.

Extended teaching and laboratory

A cache stores representations under keys. If two users request the same URL but receive private data, a shared cache keyed only by URL can cross the privacy boundary. Correctness therefore depends on cache policy, key design and authentication handling at every layer. A route returning private content should not rely on a visual sign-in screen to protect a previously cached response.

A deployment plan also needs operational evidence: detect failure, identify the affected version and recover consistently. A successful health response may prove only that a process is alive. Include a readiness check that exercises essential dependencies without exposing private data.

Worked problem Customer A loads /orders and a proxy caches the body publicly for ten minutes. Customer B opens the same URL. Explain the risk and a verification procedure.

Step-by-step reasoning 1. The proxy may serve A’s body before the origin checks B’s identity. Origin authorization cannot repair a response already returned from an unsafe shared cache.

  1. For the private response use an appropriate private/no-store policy and configure the shared layer consistently. Do not infer that one header controls every intermediary.
  1. Test with two authenticated accounts and separate sessions, verifying bodies and actual response headers through the public deployment.
  1. Invalidate unsafe cached objects if they existed. A future policy change alone may not remove content already retained.

Follow the representation through every component

The original cache investigation begins with a leaked private response. To design the complete path, distinguish the browser, intermediaries, application workers and persistent services. A browser sends a method, request target, headers and sometimes a body. A reverse proxy may terminate transport, route traffic or cache eligible responses before the application runs. The application authenticates, authorizes, validates and queries its dependencies, then returns a representation with a status and headers. Static files can be served independently of dynamic authenticated endpoints. A successful static export does not supply the missing database/authentication service.

HTTP is a protocol interface, not a particular server implementation. A URL's scheme, host and port determine an origin for browser security decisions. A path selects a route within that origin; changing a query parameter named user does not change the authenticated principal. HTTPS protects transport under its certificate and cryptographic assumptions. It does not prevent a server from returning another user's data or a cache from being configured unsafely. A browser's same-origin policy and the server's CORS response policy govern selected script access to other origins; server-side object authorization remains necessary for every client.

Headers describe representation metadata and processing policy. Content-Type tells a client how the body is represented; a declared JSON type does not validate the schema. Content-Encoding describes an encoding such as compression; it is different from the media type. Accept can express a client's acceptable representations. Redirects choose another request destination under their status semantics; distinguish redirect behavior after a mutation from a durable record of its result. A framework must send the intended status/header/body together; a helper that returns a dictionary of headers is not evidence that the public route attaches them.

Connection failure is separate from an application rejection. An HTTP error response can be received successfully over the network. A timeout after a write may mean the server committed and its response was lost. A retry policy therefore needs operation identity and reconciliation, as the original native models explain. Do not use GET as a convenient mutation route just because it is easy to paste into a browser. Report method, authenticated principal, expected version and operation identity as distinct parts of the request contract.

Freshness, validation and storage policy

A cache stores a response representation under a key. A cache hit may answer a request without executing the origin application. Key composition, permitted storage and freshness therefore become part of correctness. A public lesson and a private order listing can share the same serving infrastructure but require different policies. An authenticated page should not rely on an application's sign-in screen to protect a private representation already stored in a shared cache.

Freshness controls when a stored response can be reused without checking the origin. For a deliberately public, nonpersonal description with `max-age=60`, a cache can reuse it within the freshness policy subject to the complete applicable rules. When stale, it may need validation rather than downloading an unchanged full body. An ETag is a representation validator; a conditional If-None-Match request can produce a 304 when the selected representation still matches. The client/cache then reuses its stored body under the validated policy. A 304 has no new complete document body, so treating it as a new empty lesson is incorrect.

`no-cache` does not mean “never store”; it generally requires validation before reuse under its semantics. `no-store` directs caches not to store the response. `private` excludes shared-cache storage but can permit a private browser cache, while the precise complete directive set still matters. These policy names are not interchangeable. A policy change does not prove that an earlier unsafe copy disappeared from every cache or browser. Follow the actual cache layer's invalidation/purge and incident-handling behavior if a private object was previously stored incorrectly.

Vary tells caches that selected request-header values affect response selection. For example, representations negotiated by an appropriate request header need a compatible cache key. Adding Vary indiscriminately can reduce cache reuse and does not by itself authorize a caller or repair a cache that ignores it. Personalized responses demand an explicit design across every serving layer. Cookies and Authorization headers also affect cache handling under protocol and implementation rules; do not infer safety from one observed cache miss.

For a synthetic public lesson, compare two versions E1 and E2. A client stores body E1 with validator `lesson-1`; a later conditional request finds the same selected representation and returns 304. The displayed body remains E1. If the origin publishes E2 with validator `lesson-2`, a request using the old validator receives the new representation under the stated policy. A report that the title changed while the body remained old can reflect multiple independent caches or assets. Verify the exact changed representation and serving path rather than relying on a general “deployment succeeded” banner.

For a private order endpoint, test two independent authenticated sessions through the actual public serving path, inspect response bodies and cache headers, and confirm denied requests expose no private body. Then test the same URL after switching identity. The existing native leakage model supplies the failure mechanism. These checks are a deployment experiment, not proof that every intermediary or compromised browser behaves correctly. A fictional local application test does not establish private production serving behavior.

Window functions retain rows while adding group context

GROUP BY collapses input rows into groups. A window function computes a value across related rows while retaining a result row for each input row. Define partition, ordering and frame separately. PARTITION BY selects the independent groups. ORDER BY inside OVER establishes the analytic sequence, not necessarily the final output order. A frame chooses which rows contribute to a frame-sensitive calculation for the current row. Add a final query ORDER BY when the output needs a stable displayed sequence.

Use the following fictional accepted orders, with integer cents and a deterministic sequence key. They are report fixtures, not ledger transactions or evidence of actual customer activity.

```sql CREATE TABLE report_order ( id INTEGER PRIMARY KEY, customer TEXT NOT NULL, seq INTEGER NOT NULL, cents INTEGER NOT NULL ); INSERT INTO report_order(id,customer,seq,cents) VALUES (1,'Aster',1,500), (2,'Aster',2,500), (3,'Aster',3,200), (4,'Birch',1,700), (5,'Birch',2,-100);

SELECT id, customer, seq, cents, SUM(cents) OVER (PARTITION BY customer) AS customer_total, SUM(cents) OVER ( PARTITION BY customer ORDER BY seq,id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS running_cents, ROW_NUMBER() OVER (PARTITION BY customer ORDER BY seq,id) AS position FROM report_order ORDER BY customer,seq,id; ```

Aster's customer_total is 1200 on each of its three rows; running_cents is 500,1000,1200 and position is 1,2,3. Birch's repeated total is 600, its running values 700,600 and positions 1,2. Summing customer_total over the returned rows would give 4800 because Aster's 1200 appears three times and Birch's 600 twice. That is not the true overall 1800. A window output is still at the original order grain; adding a group value does not change the meaning of its repetition. This connects directly to the preserved join-grain investigation.

ROW_NUMBER assigns sequential positions under the declared ordering. RANK gives tied peers the same rank and leaves gaps; DENSE_RANK gives tied peers the same rank without those rank gaps. For Aster ordered by cents descending, values 500,500,200 have ranks 1,1,3 and dense ranks 1,1,2. A separate stable tie-breaker is needed when the task requires a unique first row. If id is included in the ranking ORDER BY, it can break the peer tie, so do not add it thoughtlessly while claiming tied monetary ranks. Use an outer final ordering for display or a separate row-number expression when the questions differ.

LAG and LEAD access a preceding or following row under their window definition. For Aster's sequence, LAG(cents) gives NULL,500,500. The difference from the preceding amount is undefined for the first row unless the report explicitly chooses a boundary value; calling it zero would invent an earlier observation. A three-row moving sum can use `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW`; Aster's values are 500,1000,1200 for this fixture, while a fourth 300-cent row would produce 1000 over rows 2–4. Row counts and a time interval are different frame contracts.

Be explicit about ROWS versus peer-sensitive frame behavior. An ordered aggregate's default frame may include peers with equal ordering values under the database's rules, so its first displayed row can include more than one tied record. The supplied running example specifies ROWS and a unique ordering to make its prefix interpretation unambiguous. PostgreSQL and SQLite support common window mechanisms but are not identical in every syntax, frame or NULL-handling feature; verify the engine/version used for an executable claim.

To ask for the latest order per customer, compute ROW_NUMBER in a subquery/CTE with an explicit newest-first ordering, then select position=1 in the outer query. Window calculations occur after relevant earlier query processing, so filtering a window alias directly in the same ordinary WHERE is not the same operation. Permission filtering must happen before the report window includes rows: partitioning by customer is analysis, not authorization. Loading every tenant into a shared report and hiding rows afterward can disclose derived information as well as raw records.

Integrate by preserving responsibilities and evidence

A small coherent system can keep one application server and relational database while still separating parsing, domain rules, authorization, reporting and transport adapters. Splitting into many services adds identity propagation, partial failure, deployment and tracing problems. Add that coordination only when workload and organizational constraints justify it. A system diagram should show where a request can fail, where an operation becomes durable and which component may safely retry it; boxes labelled “frontend/backend/database” alone do not answer those questions.

For the fictional work-order service, first authorize the principal and exact object/query scope. Validate proposed values, reconcile operation identity, check expected version/capacity, and commit local domain/audit changes together. Render descriptions as text and return accurate response/cache metadata. Build reports from accepted authorized rows with declared grain and window definitions. Test the precise packaged revision on disposable fixtures and verify the resulting public behavior where applicable. The existing cumulative project and rubric remain preserved, with the additional staged application connecting the newly supplied preparation.

Optional changed record and complete reasoning

Add Aster order 6 with seq=4,cents=300. Predict its customer total, full-prefix running value and three-row moving sum; then explain why summing the repeated customer_total is wrong. Next rank Aster's four amounts descending with tied equal amounts. Finally change a public lesson response from no-cache to no-store and decide whether that alone proves a previously leaked private order body was erased from a proxy.

**Model reasoning.** Aster's total becomes 1500, repeated on four order rows. Its final full-prefix running value is 1500, while the three-row frame over sequences 2,3,4 gives 500+200+300=1000. Summing repeated totals multiplies each customer's total by its row count and answers the wrong grain. Descending amounts are 500,500,300,200 with ranks 1,1,3,4 and dense ranks 1,1,2,3. A unique newest-order selection is a separate ROW_NUMBER question with an explicit sequence/tie policy. Changing storage directives for future responses does not prove deletion of an earlier unsafe cached object; inspect the actual cache, invalidation procedure and affected representation. A public lesson's policy and a private order's exposure are also different resources, so one change cannot establish the other's repair.

Evaluate on four equal criteria: request/representation/cache mechanism; exact window partition/order/frame and grain reasoning; authorized integrated state/response flow; and changed-condition evidence with clear serving/deployment limits.

Apply the idea

Customer A loads /orders and a proxy caches the body publicly for ten minutes. Customer B opens the same URL. Explain the risk and a verification procedure.

The homepage is healthy while every order request fails because the database is unavailable. What does the homepage check establish?

Read the worked reasoning

It establishes that the homepage can respond, not that the order workflow is ready. Add a bounded dependency/readiness check and a real synthetic order-read scenario using fictional data. Distinguish liveness from readiness, avoid logging credentials, and define rollback or degraded behavior when persistence is unavailable.

Check understanding

What should guide architecture choices first?

  1. Whatever hides the most errors from the visitor
    Feedback

    Failures need understandable recovery and diagnostic evidence.

  2. Workload, constraints, trust boundaries and failure behavior
    Feedback

    Architecture should address concrete responsibilities and constraints.

  3. The largest possible number of services
    Feedback

    More components increase coordination cost and may not solve a need.

Further reading

Current study directions: the original Academy lessons, preparation chapters, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters, source exercises and their historical assignment directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending. This current notice supersedes earlier textbook-supported study directions preserved below and in historical companion pages.

Use the complete original preparation chapter, preserved investigation and optional changed-record reasoning for this unit. Earlier source directions remain in immutable edition 4.

My learning →