Inside a Click

A complete reading edition of the interactive guide. Models are linked to their playable pages. Original explanations, with sources per chapter. Rails examples target 8.1.

Open the explorable → · Companion Rails feature

  1. One click
  2. Signals & cables
  3. Five layers? Seven?
  4. Your first network
  5. Across the internet
  6. Names & DNS
  7. Reliable conversations
  8. Trust & encryption
  9. HTTP
  10. Copies closer to you
  11. Inside the browser
  12. A server is a program
  13. Enough Ruby to read Rails
  14. Rails conventions
  15. A request through Rails
  16. Data that survives
  17. When requests collide
  18. HTML from Rails
  19. Who can do what?
  20. After the response
  21. Keeping it running
  22. Follow the whole click

One click

Something far away just changed.

You click. Somewhere else, a computer remembers.

Write a small note and save it. It feels immediate. But your screen and the computer keeping the note might be separated by an ocean.

This is a local teaching model of a web application. No note leaves your browser. In a real application, a successful save usually means the server accepted and persisted your change; the exact durability guarantee depends on the database and configuration. We will unpack every boundary between your finger and that write.

There are two places a program can run.

The client is the program asking for something. The server is the program providing it. Your browser draws the screen. A server can check rules and store data for everyone.

Your browser
Displays the page; reacts to your clicks; sends requests.
The application server
Runs trusted application code; reads and writes shared data.

These are roles, not kinds of hardware. Your laptop can run both a browser and a development server. One server can also be a client of a database or another API. “Server” can mean a physical machine, a virtual machine, or the program listening for requests. Ask which meaning is intended.

The internet carries. The web gives it a language.

The internet connects networks using the Internet Protocol. The web uses that infrastructure for linked resources, URLs, browsers, and HTTP. Email and many games use the internet too.

  1. Physical connections
  2. Networks exchange packets
  3. Applications exchange meaning

A private network can use internet protocols without being reachable from the public internet. A web page can exist on that private network. Wi-Fi is one way to reach a local network; a working Wi-Fi connection does not prove that your router can reach the wider internet.

Every request has a return journey.

Your browser asks for a page. The application answers with data. The browser turns that data into something you can see. Clicking Save starts another exchange.

  1. Browser: POST /notes
  2. Server: validate + write
  3. Response: 303 redirect
  4. Browser: GET the saved note

The browser often makes many requests: HTML, stylesheets, scripts, images, fonts, and API calls. Existing connections and cached responses can skip work. A navigation is not necessarily one fresh connection or one request. A redirect is a response telling the browser to make a different request.

Our specimen: a tiny Notes app.

A user owns notes. Each note has a title. We will follow POST /notes from a browser through Rails into a database, then back to an HTML page.

What the user sees
A text box, Save, and a list of notes.
What must be true
The note is valid, belongs to this user, and survives a restart.

We use this same example across the course so the abstractions have somewhere to land. Networking labs sometimes use messages or stock counters because those expose a particular mechanism more clearly. Example domains end in .test and IP addresses use documentation ranges; they are teaching addresses, not public services.

Choose the question you want to answer.

The main trail starts at the cable and builds upward. Side doors let you follow your curiosity. Open the map at any time with M; your place is saved on this browser.

Start underneath everything
What is a bit? How can light carry a note?
Start where you recognize things
What happens inside a browser or a Rails app?

There are 22 connected chapters. Each is a short deck rather than a wall of text. The numbered positions are clickable. “Look closer” contains extra precision. A branch remembers where you came from. Search by concept with /. The material follows Rails 8.1 conventions; exact generated defaults can change in later releases.

Sources: How the internet works

Signals & cables

Give a bit a body.

A bit is a choice between two possibilities.

A computer can represent a bit as 0 or 1. Agree on how to group bits, and they can stand for numbers, text, images, or instructions. Eight bits form a byte.

A physical signal is continuous, noisy, and imperfect. Digital receivers recover discrete symbols using thresholds, clocks, error correction, and coding schemes. The waveform here is an ideal binary drawing, not an accurate Ethernet or Wi-Fi modulation. Modern links often encode several bits per symbol.

The cable never sees a letter.

Text first becomes numbers. UTF-8 is an encoding: it specifies how Unicode characters become bytes. The same visible character can require more than one byte.

Text → UTF-8 bytes

A     → 41          → 01000001
é     → C3 A9       → 11000011 10101001
🙂    → F0 9F 99 82 → four bytes

Hexadecimal is a compact way to write binary: each hex digit represents four bits.

A string length can count bytes, Unicode code points, or user-perceived characters, depending on the language and operation. Some displayed characters combine multiple code points. Encoding is not encryption: anyone who knows the encoding can decode it. Compression is different again: it removes redundancy to reduce the byte count.

Same bits. Different physical carriers.

Copper carries electrical signals. Fiber carries light. Wi-Fi carries radio signals through shared air. A network interface converts between the computer’s bytes and the link’s signals.

Copper
Electrical signals over twisted pairs; interference and length matter.
Fiber
Light through glass; low loss and high capacity over long distances.
Radio
Electromagnetic waves; shared channels, interference, and obstacles.

An optical transceiver emits and receives modulated light. Repeaters and optical amplifiers help signals cross long distances. A home optical network terminal converts an access fiber connection into an interface your router can use. A modem modulates and demodulates signals; an ONT, access point, switch, and router have different jobs even when combined in one box.

The cloud has a coastline.

A typical international path crosses access networks, fiber on land, and submarine cables, then reaches a data center. Satellites are another option. A wireless first hop rarely means a wireless whole journey.

  1. Laptop · radio
  2. Home gateway
  3. Provider · fiber
  4. Submarine cable
  5. Data center

Cable routes follow geography, landing sites, available capacity, and commercial agreements. A packet may take a route that looks indirect on a map. Links and facilities are operated by many organizations. There is no single central internet computer. Redundancy helps only if the alternative routes do not share the same vulnerable infrastructure.

A wider link does not make light travel faster.

Bandwidth is capacity: bits per second. Latency is delay. Turn up the bandwidth below. A large download improves dramatically; the minimum time to cross an ocean remains.

This model adds one-way propagation and serialization for one bottleneck link. It assumes roughly 200,000 km/s through fiber, a decimal megabyte of 1,000,000 bytes, and no protocol overhead, queueing, loss, handshakes, or server work. Real end-to-end delays include all of those. RTT means round-trip time: out and back.

Delay has more than one source.

A packet takes time to enter the link, travel, wait in a queue, and be processed. A fast subscription cannot eliminate a slow server or a crowded router.

Serialization + propagation
Put the bits onto the link; let the signal travel.
Queueing + processing
Wait behind other traffic; inspect and forward the packet.

Serialization delay is packet bits divided by link bits per second. Propagation delay is distance divided by signal speed. Queueing varies with load and can dominate under congestion. Bufferbloat is excessive delay caused by large queues. Processing happens at network devices and endpoints. These costs can overlap in pipelined multi-hop networks.

Signals can arrive damaged—or not at all.

A receiver may detect corrupted data and discard it. That does not repair the application’s conversation. Higher layers decide whether to retry, wait, or continue without it.

  1. Noisy signal
  2. Error detected
  3. Frame discarded
  4. Missing data handled above

Link protocols often include error detection, such as Ethernet’s frame check sequence. Some links also retry locally or apply forward error correction. Checksums and CRCs are not defenses against a malicious sender. End-to-end integrity and reliable delivery remain distinct responsibilities.

Sources: RFC 1122, IEEE Ethernet standards, ITU optical fibre overview

Five layers? Seven?

Different maps of the same work.

A layer solves one part of the conversation.

Sending a note involves several independent problems: carry signals, reach a neighbor, cross networks, deliver to a program, and agree on what the message means.

  1. Meaning
  2. Conversation
  3. Across networks
  4. Next neighbor
  5. Signals

A protocol is a shared set of formats and rules. A layer offers a service to the layer above it. These boundaries let HTTP work over different links without knowing whether the last meter is copper or radio. Implementations do not always fit neatly into one box.

Five and seven are teaching models.

Use the switch to compare the stacks. The five-layer model separates physical and link work. The seven-layer OSI model also separates presentation and session functions.

The Internet architecture is commonly described with four layers: application, transport, internet, and link. Five-layer teaching models split link into data link and physical. OSI has seven. These are not seven programs that every request must call. TLS, QUIC, and many practical systems cross the conceptual boundaries.

Presentation and session are jobs, not compulsory boxes.

OSI’s presentation layer concerns representation. Its session layer concerns managing dialogue. Real web stacks distribute those jobs among application libraries and protocols.

Presentation-like work
Encoding, serialization, compression, encryption.
Session-like work
Establishing, resuming, and coordinating a dialogue.

Do not equate OSI session with a Rails login session. Rails sessions are application state carried across HTTP requests. Likewise TLS is often drawn near presentation, but the practical TLS stack over TCP does not implement OSI as seven literal modules. Knowing the mapping is useful; forcing every technology into exactly one box is not.

A message travels inside other messages.

Each layer adds information for its job. At the receiver, the layers interpret their own information and pass the payload upward. This is encapsulation.

  1. HTTP request
  2. TLS records
  3. TCP segments
  4. IP packets
  5. Link frames

This is a conceptual containment diagram, not a guarantee that one HTTP request equals one TLS record, one TCP segment, or one IP packet. TCP is a byte stream. Large messages span many packets; boundaries can be split or combined. HTTP/3 instead uses QUIC over UDP.

Some addresses survive the trip. Others change at every hop.

The frame gets you to the next local device. The IP packet identifies a destination across networks. At a router, the outgoing link gets a new frame.

Next-hop identity
A link destination, such as the gateway’s MAC address. Changes between links.
End-to-end identity
Destination IP address and transport port. Usually retained; NAT is a major exception.

Routers strip the incoming link framing and construct suitable outgoing framing. They decrement the IPv4 TTL or IPv6 Hop Limit. IPv4 header checksums change accordingly. NAT can rewrite IP addresses and ports. A proxy can terminate one connection and open an entirely different one.

Use layers to locate a failure.

If Wi-Fi is disconnected, changing a Rails controller will not help. If Rails returns a validation error, the network already carried an application response.

No route or connection timeout
Look below the application first: path, firewall, listener.
HTTP 422 with a validation message
The application received the request and rejected its content.

Symptoms are evidence, not a perfect diagnosis. A proxy can generate an HTTP error before Rails sees anything. A timeout can happen during a database call after a TCP connection succeeds. Test the next boundary that can discriminate between your hypotheses.

Sources: RFC 1122, OSI basic reference model

Your first network

Before a packet meets the internet.

Your computer needs a network interface.

A network interface controller connects a computer to a link. Ethernet and Wi-Fi use link-layer addresses called MAC addresses for local delivery.

  1. Application bytes
  2. Operating system network stack
  3. Network interface
  4. Local link

A device can have several interfaces and addresses at once. A MAC address belongs to an interface in a link context, not permanently to a person. Software can change or randomize it. It generally does not travel across the internet inside every later Ethernet frame.

An Ethernet frame has a local destination.

A frame includes a destination MAC, a source MAC, a type field, a payload, and an error check. A receiving interface accepts relevant frames and passes their payload upward.

Simplified Ethernet frame

[ destination MAC ][ source MAC ][ type ]
[              payload: an IP packet          ]
[ frame check sequence ]

EtherType identifies the payload protocol, such as IPv4 or IPv6.

Real Ethernet framing includes additional transmission details and may include VLAN tags. The maximum transmission unit, or MTU, bounds the network-layer payload a link can carry. A common Ethernet IP MTU is 1500 bytes, but it is not universal. Path MTU discovery helps endpoints avoid sending packets too large for a path.

A switch learns by watching who speaks.

A switch remembers which port a source MAC arrived on. If it knows the destination, it forwards there. If not, it floods eligible ports on the same local network.

This is a simplified learning bridge with three hosts. Real switches age out entries, separate VLANs, handle broadcast and multicast, and avoid loops with protocols such as spanning tree. “Flood” means forwarding locally, not broadcasting the data across the whole internet.

Wi-Fi shares airtime.

An access point bridges wireless devices into a local network. Nearby devices contend for radio airtime; interference and weak signals can cause retries. More devices can mean more waiting.

Access point
Connects wireless stations to the local network.
Router
Forwards IP packets between different networks.

A home router often includes the router, switch, access point, DHCP server, NAT, and firewall in one enclosure. These remain separate functions. Wi-Fi link encryption protects the wireless hop; HTTPS protects an application connection to its TLS endpoint. One does not replace the other.

How did the laptop get an IP address?

On many IPv4 networks, DHCP leases an address and provides settings such as a subnet mask, gateway, and DNS resolver. IPv6 can use router advertisements and SLAAC, sometimes with DHCPv6.

  1. Join link
  2. Discover configuration
  3. Get address + routes
  4. Learn DNS resolver

IPv4 DHCP commonly uses a discover, offer, request, acknowledge exchange. IPv6 Stateless Address Autoconfiguration uses advertised prefixes; clients create addresses and check for duplicates. DHCPv6 is not the standard mechanism for learning an IPv6 default gateway: router advertisements do that. Static configuration is also possible.

The first delivery is often to your gateway.

Your routing table chooses a next hop. For IPv4 Ethernet, ARP finds the MAC for that local IP address. IPv6 uses Neighbor Discovery. The next hop receives the frame and forwards the packet.

  1. Remote IP destination
  2. Choose default gateway
  3. Resolve gateway’s local address
  4. Send frame to gateway

For an on-link destination, resolve that destination directly. For an off-link destination, resolve the router’s address, not the remote server’s MAC. Neighbor caches avoid repeating discovery for every packet. ARP and Neighbor Discovery have their own local trust and security considerations.

Sources: RFC 826, RFC 2131, RFC 4861

Across the internet

Many networks. No global switch.

IP delivers packets on a best-effort basis.

The Internet Protocol gives packets source and destination addresses. Routers forward toward a destination. IP itself does not promise delivery, order, or freedom from duplicates.

  1. Your network
  2. Provider network
  3. Other networks
  4. Destination network

An IPv4 address has 32 bits; IPv6 has 128. Addresses are assigned to interfaces and scoped by routing context. Routers normally make forwarding decisions from destination prefixes, not from your note’s title. Reliable application behavior must be built on stronger protocols and application rules.

A prefix groups addresses.

The /24 in an IPv4 prefix says the first 24 bits identify the network portion. A more specific prefix describes a smaller set of addresses.

This lab uses ordinary IPv4 subnet arithmetic with /16 through /30. For these conventional subnets, the first address is the network address and the last is broadcast, leaving two fewer assignable host addresses. /31 point-to-point and /32 host routes have different conventions. IPv6 has no broadcast and does not follow this host-count rule.

The most specific matching route wins.

A router compares the destination with its forwarding table. If multiple entries match, it uses the longest prefix. A default route matches everything when no more specific entry wins.

Example forwarding table

0.0.0.0/0        → upstream A
203.0.113.0/24    → upstream B
203.0.113.128/25  → upstream C

203.0.113.140 matches all three → C

A /25 matches more address bits than a /24 or /0.

This describes longest-prefix matching in forwarding. How a router chose which route to install for a given prefix is a separate control-plane decision involving routing protocols, policy, metrics, and possibly multiple equal-cost paths. A default route is not proof that the upstream can reach the destination.

Cut a link. Does the packet still arrive?

A network can survive a failed connection if another path exists. Try cutting different links. Then lower the hop limit until the packet expires before reaching the server.

This lab recomputes a shortest-hop path immediately. It illustrates connectivity and hop limits, not the actual BGP selection algorithm or convergence delay. Real routing takes time to react, is constrained by policy, and can temporarily loop or black-hole traffic. TTL in IPv4 is practically a hop count; it is not a wall-clock deadline.

The internet is a federation.

An autonomous system is a network or group of networks under a routing policy. Border Gateway Protocol—BGP—exchanges reachability between them.

  1. Network announces a prefix
  2. Neighbor applies policy
  3. Route propagates
  4. Forwarding tables change

BGP carries path information including autonomous-system paths. Route selection involves local preference and policy; it is not simply geographical shortest distance. Within a network, other protocols and mechanisms distribute routes. Route leaks and hijacks can send traffic the wrong way. RPKI route-origin validation helps check who is authorized to originate a prefix, but is not a complete proof of a whole path.

Connections between networks have owners.

Networks may peer to exchange traffic or buy transit to reach other networks. An internet exchange point provides shared infrastructure for networks to interconnect.

Peering
Exchange traffic under a bilateral or multilateral agreement.
Transit
Pay an upstream for broader network reachability.

Physical capacity, business agreements, resilience, and traffic engineering shape routes. A CDN can place content within or near an access provider, shortening the path. Anycast advertises the same IP prefix from multiple locations; routing selects a reachable instance, not necessarily the one with the shortest physical distance.

NAT rewrites an address. A firewall enforces a policy.

A home IPv4 gateway often maps many private connections onto one public address using ports. That is network address translation. A firewall decides which traffic is allowed.

One NAT mapping

Inside:  192.168.1.7:51000 → 203.0.113.8:443
Outside: 198.51.100.4:62001 → 203.0.113.8:443

Reply to :62001 → map back to 192.168.1.7:51000

The example addresses are reserved for documentation.

NAT maintains state and can complicate incoming connections and peer-to-peer communication. Carrier-grade NAT adds another translation layer. NAT is not synonymous with a firewall or encryption, even though many devices combine these features. An IPv6 network can use globally routable addresses and still enforce a strict stateful firewall.

IPv6 changes the address space, not the purpose of the web.

IPv6 offers a much larger address space, different headers, and Neighbor Discovery. Many networks run IPv4 and IPv6 together. Browsers can try available paths to avoid waiting on a broken one.

IPv4
32-bit addresses; ARP on Ethernet; NAT common.
IPv6
128-bit addresses; Neighbor Discovery; no broadcast.

IPv6 routers do not fragment packets in transit. An endpoint adjusts after Packet Too Big feedback or packetization-layer discovery. ICMP carries important control messages, not just ping. Blocking all ICMP can break useful functions. Traceroute infers hops using expiring TTL/Hop Limit probes; its output is not a complete or guaranteed map of the return path.

Sources: RFC 791, RFC 8200, RFC 4271, RFC 3022

Names & DNS

Find an address before sending a request.

A URL contains several different instructions.

In https://notes.test:443/notes/7?view=full#comments, the hostname is only one part. DNS resolves that name. HTTP carries the path and query. The fragment stays in the browser.

Take the URL apart

https        scheme: how to access it
notes.test   hostname: who to contact
443          port: which service
/notes/7     path: which resource
?view=full   query: additional input
#comments   fragment: local document navigation

The default HTTPS port is 443 and can be omitted. A URL can contain an IP address instead of a domain name. Percent encoding represents characters in URL components; it does not encrypt them. Query strings often appear in logs and history, so they are a poor place for secrets.

DNS is a distributed naming system.

Your device asks a recursive resolver. On a cache miss, that resolver follows delegations: root, top-level domain, authoritative nameserver. The authoritative server supplies the relevant answer.

  1. Browser / OS
  2. Recursive resolver
  3. Root → .test delegation
  4. Authoritative answer

This is the conceptual sequence for a cold lookup, using an illustrative .test hierarchy. In reality .test is reserved for testing, not a public delegated production zone. Resolvers cache intermediate delegations as well as final answers. The device usually does not contact each of these servers itself. The OS, browser, and local network may each contribute caches.

A name can have more than one kind of answer.

An A record contains an IPv4 address. AAAA contains IPv6. Other records identify aliases, mail servers, authoritative servers, and additional metadata.

Address and alias
A, AAAA, CNAME: addresses or another name to resolve.
Delegation and other services
NS, MX, TXT: nameservers, mail routing, and text data.

A CNAME does not redirect the browser to a different URL; DNS resolution continues under the alias. An HTTP redirect changes the resource the browser requests. MX is for mail exchange, not choosing the web server. DNS answers may return several addresses. HTTPS/SVCB records can advertise service parameters.

Changing DNS does not erase cached answers.

Resolve the name, then change the authoritative address. Until the cached answer expires, this resolver can keep returning the old address. Advance its clock and try again.

TTL means time to live, measured in seconds for DNS records. Caches generally count down the TTL remaining at receipt. Lowering the authoritative TTL now does not retroactively shorten an answer already cached under an older TTL. Negative answers can be cached too. Some resolvers may serve stale data under specific failure policies; this model assumes ordinary expiry.

Moving a website is a coordination problem.

Prepare the new server first. Reduce TTL ahead of time if useful. Change DNS. Keep the old endpoint working while earlier answers expire. Remember that existing connections may outlive DNS answers.

  1. Prepare destination
  2. Let old TTLs expire
  3. Change answer
  4. Overlap old + new

Domain registration, delegation, DNS records, TLS certificates, and application deployment are different systems. Changing one does not automatically configure the others. Nameservers at the registrar must delegate correctly; both endpoints need the right application and certificates. “DNS propagation” often describes old cached information aging out, not a single update sweeping every computer.

Private lookup and authentic lookup are different promises.

DNS over HTTPS can encrypt the connection to a resolver. DNSSEC can validate signed DNS data. Neither guarantees that a website’s application is honest or bug-free.

Encrypted transport
Hides the query from observers on that hop; the resolver still sees it.
Signed DNS data
Helps validate origin and integrity when the chain is signed and checked.

DNSSEC authenticates DNS data through a chain of trust; it does not encrypt queries. DoH changes the transport of DNS messages. HTTPS certificate validation is still necessary even if DNSSEC validates a name’s records. Privacy also depends on who runs the resolver and what metadata other connections reveal.

Sources: RFC 1034, RFC 1035, RFC 4033, RFC 8484

Reliable conversations

Packets are not yet a conversation.

An address finds a host. A port finds a service.

Many programs share one network interface. A transport port helps the operating system deliver incoming data to the right socket. A socket is a program’s interface to network communication.

A typical connection identity

TCP
client 192.168.1.7 : 51000
server 203.0.113.8 : 443

protocol + source IP/port + destination IP/port

A server can handle many clients on port 443 because their connection identities differ.

A listening socket accepts connections; each accepted TCP connection has its own state. The client usually chooses an ephemeral source port. A port number is not proof of the application protocol or security: using port 443 alone does not magically provide HTTPS. UDP sockets can send messages without TCP-style connection setup.

UDP preserves messages without promising arrival.

User Datagram Protocol sends datagrams: bounded messages. They may be lost, duplicated, or reordered. An application decides whether lateness, loss, or retries matter for its job.

A live voice sample
Late data may be less useful than missing data.
A saved document
Missing content must be detected and recovered.

UDP has ports and an integrity checksum, but no built-in acknowledgement/retransmission or congestion-control mechanism. Applications and protocols using it still need to behave responsibly under congestion. UDP does not inherently mean “fast” or “unreliable app”: QUIC builds reliable, congestion-controlled streams on top of it.

TCP first agrees to have a conversation.

TCP exchanges SYN, SYN-ACK, and ACK to establish connection state and sequence-number synchronization. That setup costs time before ordinary application data can flow.

  1. Client → SYN
  2. Server → SYN + ACK
  3. Client → ACK
  4. Connection established

TCP sequence numbers identify positions in a byte stream. The handshake also negotiates options such as receive window scaling and selective acknowledgements. It does not authenticate the server’s domain name or encrypt the data. TLS normally adds those properties above TCP. Connection reuse avoids paying setup cost on every HTTP request.

Out of order is fine. A missing piece is not.

Deliver chunks in any order. In TCP mode, later bytes wait for the gap before reaching the application in order. Retransmit the missing chunk. In datagram mode, each delivered message stands alone.

Each tile stands for one chunk of a TCP byte stream or a separate UDP-style datagram. Real TCP numbers bytes, not these tile labels, and does not preserve application message boundaries. It acknowledges received data, detects likely loss, and retransmits. A connection can still fail permanently; reliability is not a promise that an unreachable peer will eventually answer. A TCP acknowledgement comes from the peer’s TCP stack. It does not prove the application read, validated, or persisted those bytes.

Do not drown the receiver—or the network.

Flow control limits sending to what the receiver can buffer. Congestion control adjusts sending to what the path appears able to handle. These solve different bottlenecks.

Receiver window
“I have room for this many more bytes.”
Congestion window
“The path seems able to sustain this much in flight.”

A sender is constrained by both windows, among other limits. Congestion algorithms react to acknowledgements, loss, explicit congestion signals, and timing. They are not all identical. Bandwidth-delay product is capacity multiplied by RTT: it estimates how much data must be in flight to fill the path. Slow start grows the sending allowance during startup; it does not mean the link speed itself changes.

Many requests can share one connection.

HTTP/2 multiplexes streams over TCP. But TCP still exposes an ordered byte stream: a missing segment can delay multiple HTTP streams while the gap is repaired.

  1. HTTP streams A + B + C
  2. One TCP byte stream
  3. One missing segment
  4. Delivery waits at the gap

Multiplexing avoids HTTP/1.1’s common need for multiple parallel connections and its response-ordering limitations. It does not remove TCP’s transport-level head-of-line blocking. Stream prioritization, server scheduling, flow control, and network congestion also influence how quickly each resource finishes.

QUIC moves reliability above UDP.

HTTP/3 uses QUIC. QUIC provides reliable streams, congestion control, and TLS-based security. Loss on one stream need not block delivery on another stream with all its required data.

HTTP/2
HTTP streams → TLS → TCP → IP
HTTP/3
HTTP streams → QUIC with TLS → UDP → IP

QUIC also supports connection migration using connection IDs, useful when a device changes networks. Initial handshakes usually require a round trip; resumption can permit 0-RTT data with replay risks and restrictions. HTTP/3 does not eliminate congestion, loss, application dependencies, or all head-of-line effects. A server and browser must support it, and networks must allow the traffic.

Sources: RFC 9293, RFC 768, RFC 9000, RFC 9114

Trust & encryption

The network can carry data it must not read.

Assume someone can observe the path.

On an unencrypted connection, an intermediary may read or modify application data. Transport Layer Security protects the confidentiality and integrity of a connection and usually authenticates the server.

Without TLS
An on-path observer may read or alter HTTP content.
With correctly validated TLS
Content is encrypted and tampering is detected between TLS endpoints.

TLS protects a connection, not the whole lifecycle of data. The server can read what it receives, and malware on either endpoint can read plaintext. TLS does not fix authorization bugs, insecure password storage, or accidental logging of secrets. Authentication of the user is an application concern.

A key controls who can recover the message.

Encryption transforms readable data into ciphertext. Decryption recovers the original data with the right key. With symmetric encryption, both ends use shared secret key material.

Plaintext + key → ciphertext
Protect the message while it crosses an untrusted path.
Ciphertext + key → plaintext
An intended endpoint can recover the message.

A cryptographic key is data, not a human password sent along with every message. Secure encryption must also handle details such as nonces correctly. Modern TLS uses authenticated encryption, which detects modification as well as hiding content. Encoding, hashing, and encryption are different operations: only encryption is intended to be reversible with a secret key.

A signature proves control of a private key.

A public/private key pair supports asymmetric cryptography. For a digital signature, the holder signs with the private key. Others verify the signature with the public key. Verification does not reveal the private key.

  1. Private key stays secret
  2. Sign the handshake data
  3. Public key checks signature
  4. Altered data fails verification

A signature proves that the matching private key authorized that signed data, under the security assumptions of the scheme. It does not by itself prove who owns that key. A certificate binds a key to an identity such as a hostname, and a certificate authority signs that binding. Not every public-key algorithm supports both encryption and signatures.

Key agreement creates a secret without sending that secret.

The two peers exchange public contributions. Each combines the other’s contribution with its own private information to derive shared secret material. An observer sees the exchange but should not be able to derive the same secret.

Agreement
Derive shared material across an observable network.
Authentication
Prove whose exchange you participated in.

Unauthenticated key agreement is vulnerable to an active intermediary establishing separate secrets with both sides. TLS authenticates its handshake to prevent that substitution in its trust model. Ephemeral keys support forward secrecy: later compromise of the certificate’s long-term key should not reveal previously recorded traffic from those handshakes. Exact cryptographic algorithms are a further field of study.

Public keys establish trust. Shared keys carry the bulk data.

Modern TLS uses public-key techniques for authentication and key agreement. The peers derive symmetric traffic keys to protect the actual data efficiently.

  1. Agree on parameters
  2. Establish shared secrets
  3. Authenticate handshake
  4. Encrypt application records

In a typical TLS 1.3 certificate handshake, ephemeral Diffie–Hellman key agreement contributes shared key material, and the server signs handshake information using the private key associated with its certificate. The client checks the signature and certificate chain. The certificate’s public key is not simply used to encrypt every byte of your note. Symmetric authenticated encryption protects records.

Encryption to the wrong computer is not enough.

The browser checks whether the certificate is trusted, valid for this hostname, and within its validity period. Try breaking one of those conditions.

This model isolates a few certificate checks, not a complete TLS implementation. Actual validation includes chain building, signatures, key usage, policies, and other checks. A publicly trusted certificate normally proves control of a domain under a CA’s validation process; it does not certify that the business is honest. The encrypted display is an illustration, not cryptography.

A TLS handshake is an exchange, not a secret password sent across the wire.

In a typical fresh TLS 1.3 handshake, the client sends a hello with key-share material. The server replies with its key share and authenticated handshake messages. Both derive keys and verify the handshake.

  1. ClientHello + key share
  2. ServerHello + authenticated messages
  3. Client Finished
  4. Protected HTTP data

A normal TLS 1.3 handshake adds roughly one RTT before the client can send ordinary application data, after TCP establishment. Network conditions and implementation details affect the actual timing. Resumption can reduce work; 0-RTT early data has replay risks. Do not treat a fixed “eight round trips for HTTPS” diagram as a universal modern rule.

HTTPS hides content, not all metadata.

On-path observers can still see IP addresses, timing, and traffic sizes. A TLS terminator sees the plaintext. Hostname visibility depends on DNS transport, TLS features, and network configuration.

Usually protected
HTTP path, query, headers, cookies, and body inside TLS.
Still observable on the path
Endpoints’ network addresses, packet sizes, and timing.

Traditional TLS Server Name Indication exposes a hostname in the ClientHello. Encrypted Client Hello can reduce that exposure where supported and deployed. DNS may reveal the name separately. A URL fragment is not sent in the HTTP request at all. HTTPS also does not prevent the browser or endpoint from recording the full URL.

Where TLS ends is a design decision.

A CDN or reverse proxy often terminates the browser’s TLS connection, then sends a separate request to the app. That second connection has its own security requirements.

  1. Browser ⇄ TLS
  2. Edge / reverse proxy
  3. Separate upstream connection
  4. Rails / Puma

Certificates expire and need renewal. Private keys must remain protected. Automated issuance such as ACME reduces manual work but still needs monitoring. HSTS tells a browser to use HTTPS for a host under a stored policy; it is not a replacement for a valid certificate. A reverse proxy is a trust boundary: forwarded headers should only be trusted from known proxies.

Sources: RFC 8446, Let’s Encrypt: how it works

HTTP

Give a request a precise meaning.

HTTP is a request and a response.

A client sends a method, a target, headers, and sometimes a body. A server returns a status, headers, and sometimes a body. These semantics survive changes in the wire encoding.

The lab shows a readable HTTP/1.1-like representation. HTTP/2 and HTTP/3 use binary framing and different header encoding, not these literal text lines. The behavior is a local Notes API model, not a network call. HTTP is stateless in the sense that each request has independently interpretable semantics; applications can still maintain state.

The request target is not a filename.

GET /notes/7 might load a database row and render a template. The path identifies a resource in the application’s interface. The router decides what code handles it.

Readable request example

GET /notes/7 HTTP/1.1
Host: notes.test
Accept: text/html
Cookie: session=…

Headers add context. A blank line separates headers from an optional body.

The host lets a server distinguish sites sharing an address. Query parameters are part of the request target; a fragment is not. Reverse proxies may rewrite paths or host information before forwarding. The HTTP message still needs framing rules to indicate body length or streaming boundaries.

Methods express intent.

GET reads a representation. POST submits work or creates something. PUT requests replacement. PATCH requests a partial change. DELETE requests removal. A server must implement their semantics honestly.

Safe
GET and HEAD should not request state-changing side effects.
Idempotent
Repeating PUT or DELETE has the same intended effect as once. POST generally does not.

Safe methods can still cause incidental logging or metrics. Idempotent does not mean the response status must be identical: deleting a missing resource may produce a different response from the first delete. A particular PATCH operation can be idempotent, but PATCH is not defined as universally idempotent. An idempotency key can give a specific POST operation retry safety.

REST organizes the interface around resources.

A note has an address. Methods describe operations on it. Representations describe its current state. Rails’ resource routes are a practical convention for this style.

A resource-shaped interface

GET    /notes       list
POST   /notes       create
GET    /notes/7     show
PATCH  /notes/7     update
DELETE /notes/7     destroy

Rails also provides GET routes for the new and edit forms.

REST is an architectural style with constraints including a uniform interface, stateless interactions, cacheability, and layered components. A CRUD JSON API is not automatically a complete realization of REST. HTML is also a representation and its links and forms provide controls for further actions. RPC-style endpoints are another design choice; choose semantics deliberately.

The status tells you what happened at the HTTP boundary.

2xx indicates success. 3xx often redirects or supports cache validation. 4xx reports a request-side problem. 5xx reports a server-side failure. Read the actual status and context.

200 · 201 · 204
Representation returned · resource created · success with no content.
303 · 304
Fetch another location · reuse a cached representation.
401 · 403 · 404 · 422
Credentials needed · forbidden · not found · understood but unprocessable.

401 is associated with authentication and a WWW-Authenticate challenge, despite its historical “Unauthorized” name. A browser app often redirects to login instead. 404 may deliberately conceal a resource a user cannot access. 500 indicates an unexpected server error; 502 and 504 often come from a gateway or proxy, while 503 can indicate temporary unavailability.

Headers describe the representation and the rules around it.

Content-Type describes what is in the body. Accept expresses what the client can receive. Cache, compression, authentication, and cookie behavior are also carried in headers.

Response example

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: private, max-age=0
ETag: "note-7-v3"

<h1>A small note</h1>

The body might instead be JSON, an image, a file, or a stream.

Content-Encoding such as gzip or br indicates a compression coding, separate from the media type and character encoding. Vary tells caches which request headers influence the selected representation. Content-Length counts bytes, not characters. User-controlled headers and body content are untrusted inputs, not commands to execute.

The language is stable; the transport evolves.

HTTP/1.1 uses text-like headers and connection reuse. HTTP/2 adds binary framing and multiplexing over TCP. HTTP/3 maps HTTP semantics onto QUIC.

What stays
Methods, statuses, fields, resources, caching semantics.
What changes
Framing, compression, multiplexing, connection behavior, loss recovery.

HTTP/2 and HTTP/3 encode header fields compactly using HPACK and QPACK respectively. These details matter for protocol implementers and some security or performance investigations. A Rails controller usually operates above them because a server or proxy decodes the wire protocol into request information.

A response can last longer than a page load.

Servers can stream data as it becomes available. Server-Sent Events keeps a server-to-browser event stream. WebSocket establishes a bidirectional channel with its own message framing.

  1. Ordinary response: finishes
  2. SSE: server → browser events
  3. WebSocket: messages both ways

HTTP streaming does not guarantee every small write immediately appears at the browser; application, proxy, compression, and network buffering matter. SSE uses HTTP and supports event IDs for reconnection patterns. WebSocket setup depends on the HTTP version and supported mechanisms. Long-lived connections consume capacity and need reconnection logic.

Sources: RFC 9110, RFC 9112, RFC 9113, RFC 9114

Copies closer to you

Sometimes the fastest request does not travel.

There is more than one place to keep a copy.

A browser can reuse a response. A shared proxy or content delivery network can serve many users. Rails can cache computed fragments or data before it constructs a response.

  1. Browser cache
  2. CDN / shared cache
  3. Rails cache
  4. Database

These caches store different things and obey different rules. A CDN stores HTTP representations under a cache key; a Rails fragment cache stores rendered pieces; a database buffer cache stores pages. Do not assume clearing one clears the others. For private notes, public shared caching is usually inappropriate without careful design.

A fresh copy can skip the server entirely.

Set the cache lifetime. Change the origin’s version. Fetch again before and after expiry. A fresh cached response can remain unchanged even when the origin has newer content.

This lab models a single private browser cache with instant requests and ETag validation. It omits Age propagation, shared-cache rules, Vary, stale directives, network failures, and concurrent requests. It shows why freshness is a permission to reuse, not a live guarantee that the origin has not changed.

Stale does not mean useless.

A cache can ask whether its stored representation still matches. With an ETag validator, the server can return 304 Not Modified, letting the cache reuse its existing body.

  1. Cached ETag: v3
  2. If-None-Match: v3
  3. Origin still v3 → 304
  4. Reuse body already held

A 304 saves body transfer but still requires a round trip and validation work. If the representation changed, a normal 200 response supplies the new body. ETags are opaque validators, not necessarily cryptographic hashes. Last-Modified and If-Modified-Since offer time-based validation with different precision constraints.

“No-cache” does not mean “do not store.”

no-cache requires validation before reuse. no-store forbids storing the response in an HTTP cache. private excludes shared caches while allowing private ones.

no-cache
May store; must successfully validate before reuse.
no-store
Do not store in an HTTP cache.
private
A shared cache must not store; a private cache may.

Cache-Control interacts with other directives and response properties. It is not a complete privacy policy for screenshots, browser history, application logs, service worker storage, or a user saving a file. Sensitive responses need deliberate policies at every relevant boundary. Vary: Cookie is not a universal fix for accidentally caching private pages.

Changing the name can make invalidation simple.

A fingerprinted asset has a URL tied to its content. Change the CSS and its fingerprint changes. The HTML points to a new URL while older versions remain safe to cache.

Content-addressed asset URLs

/assets/application-a91f.css  ← old content
/assets/application-3b72.css  ← new content

HTML now references application-3b72.css

Long-lived caching works when the URL changes with the bytes.

Do not overwrite immutable content behind an unchanged URL. Keep old assets available long enough for cached HTML and in-flight sessions. Application data is more difficult: a note title might appear in a page, list, count, and search index, each with its own cache key or invalidation mechanism.

Caching changes where work happens.

Compression reduces transferred bytes. A CDN shortens some network paths. A cache hit avoids origin work. None of these fixes a database write that takes too long.

Read path
Copies can remove repeated work when reuse is correct.
Write path
A mutation still needs authorization, correctness, and a durable outcome.

Caching authenticated content requires attention to identity and representation variants. Cache stampedes happen when many requests recompute an expired item simultaneously. Locking, jitter, or serving stale values under an explicit policy can help. Measure hit rates and end-to-end latency; an unused cache adds complexity without benefit.

Sources: RFC 9111, HTTP caching, Caching with Rails

Inside the browser

Bytes become a living document.

HTML describes a document.

The browser parses HTML into a Document Object Model: a tree of elements and text. A heading, a form, and a button have meaning before they have a visual style.

HTML in the browser

<main>
  <h1>My notes</h1>
  <form action="/notes" method="post">
    <label>Title <input name="note[title]"></label>
    <button>Save</button>
  </form>
</main>

A real Rails form also includes framework-generated security fields.

The live DOM may differ from the original source because the parser repairs invalid structures and JavaScript changes nodes. Semantic elements supply built-in behavior and accessibility information. A clickable div is not equivalent to a button: you would need to recreate keyboard, focus, and other semantics.

Style and behavior are separate powers.

CSS changes presentation. JavaScript can change state and react to events. Try removing either from the same small document. Its content and structure can remain useful.

This controlled specimen toggles a stylesheet class and an event handler. It is not an unrestricted HTML editor. Real CSS uses the cascade, inheritance, selector specificity, and source order to resolve competing declarations. JavaScript can modify the DOM and styles, but the browser’s rendering engine decides the pixels.

CSS decides which rule wins, then sizes the box.

A selector chooses elements. The cascade resolves competing declarations; inheritance supplies some values from ancestors. The box model adds padding and borders around content. Change the box below.

For ordinary author declarations without layers or !important, specificity and source order help decide conflicts. The full cascade also considers origins, importance, layers, and other rules. Width under content-box describes the content; under border-box it includes padding and border. Margin sits outside the border. Flexbox and Grid arrange boxes; responsive media queries change rules for conditions such as available width.

Pixels are the result of a pipeline.

After parsing, the browser calculates styles and layout. It paints visual content and composites layers. Changing geometry may require more work than moving an already composited layer.

  1. DOM + style rules
  2. Computed styles
  3. Layout geometry
  4. Paint
  5. Composite

Browsers optimize and interleave this pipeline. Some off-screen work can be deferred. Layout determines boxes and positions; painting records or draws appearance; compositing combines layers. Not every transform is free, and excessive layers cost memory. Font and image loads can shift layout unless space is reserved.

An event connects an action to code.

Clicking a button produces an event. A listener runs a function. That function might change the document, start a request, or allow the browser’s default form submission.

JavaScript in the browser

button.addEventListener("click", () => {
  status.textContent = "Ready to save";
});

The callback runs when the event is dispatched, not when the listener is registered.

Events often propagate through ancestors, allowing event delegation. preventDefault cancels a default action when allowed; stopPropagation affects propagation instead. Avoid using those interchangeably. A browser can handle ordinary links and forms without your JavaScript. Enhancements should not unnecessarily remove those capabilities.

A long task makes the page feel frozen.

The main thread cannot handle an input callback while it is busy running another task. Increase the work time. Watch the input wait even though the network is fast.

This is a scheduling model, not an actual CPU freeze. JavaScript executes a task to completion, then microtasks are drained before later tasks and rendering opportunities. await lets a function yield while waiting, but CPU-heavy synchronous code still blocks. Web workers can move suitable computation off the main thread; they cannot directly manipulate the DOM.

Fetch gets data. It does not decide what to draw.

JavaScript can request a resource with fetch. The response can contain JSON or HTML. Application code must interpret it and update the interface. A traditional form navigation lets the browser load the returned page.

Browser JavaScript

const response = await fetch("/notes/7.json");
if (!response.ok) throw new Error("Request failed");
const note = await response.json();
title.textContent = note.title;

fetch does not reject merely because the server returned HTTP 404 or 500.

Network failures reject the fetch promise, while ordinary HTTP error responses resolve to a Response object. Credentials and cross-origin access have explicit rules. JSON is a data format, not executable Ruby or JavaScript. Parsing a JSON response does not automatically insert it safely into the page.

Origins separate applications in the browser.

An origin is scheme, host, and port. The same-origin policy restricts one origin reading another’s data. CORS lets a server permit some cross-origin reads.

Same origin
https://notes.test/a and https://notes.test/b
Different origins
https://notes.test and https://api.notes.test

CORS is enforced by browsers, not a general API authorization mechanism. Some cross-origin requests can be sent even when JavaScript cannot read the response; more complex requests often require a preflight. That distinction is why CORS does not replace CSRF defenses. Credentialed cross-origin access also requires the appropriate credentials settings and explicit allowed origins.

The browser keeps state of its own.

Cookies can accompany requests. Local storage and IndexedDB keep data for scripts. Service workers can intercept requests under their scope. None of this automatically becomes the server’s database.

Server-related state
Cookies identify sessions when sent under their scope and policy.
Local application state
Storage and service workers can support offline behavior.

Service workers require a secure context, except special local development cases. Offline writes need reconciliation when connectivity returns. A responsive, accessible interface also needs labeled controls, keyboard access, sensible focus, contrast, and reduced-motion handling. The accessibility tree helps assistive technologies interpret semantic structure; visual resemblance alone does not provide it.

Sources: How browsers work, JavaScript execution model, CORS, Accessibility

A server is a program

The operating system meets your app.

A running program has memory and a lifetime.

A process is a running instance of a program. It has memory and resources managed by the operating system. Restarting it discards ordinary in-memory objects.

  1. Program files on disk
  2. Start process
  3. Objects in memory
  4. Process exits

A variable in a controller is not permanent storage. Processes usually have separate address spaces. Threads share a process’s memory, so shared mutable state needs coordination. Durable data belongs in a storage system with appropriate persistence guarantees, not in a Ruby global variable.

A listener waits for connections.

A server binds a socket to an address and port. The operating system receives network data and makes it available to the server process. No listener means the request cannot reach your application there.

  1. Network interface
  2. Kernel network stack
  3. Listening socket
  4. Accepted connection
  5. Application

A bind address such as 127.0.0.1 limits a listener to the local host. Binding to all interfaces makes it potentially reachable through other interfaces, subject to network policies. A connection refusal differs from a timeout, though intermediaries can change symptoms. Listen backlogs, connection limits, and file descriptors are finite resources.

A reverse proxy hands traffic to an application server.

A reverse proxy can terminate TLS, serve assets, and distribute requests. Puma runs Ruby web applications. Rack defines the Ruby interface between server and application.

  1. Browser
  2. Reverse proxy
  3. Puma
  4. Rack middleware
  5. Rails

These are roles, not mandatory separate machines. A development setup can reach Puma directly. A deployment might include a CDN before the proxy. Middleware can log, handle sessions, reject a request, or transform a response. Rails receives a request after lower-level wire details have already been decoded.

Rack turns networking into an ordinary Ruby call.

A Rack application receives an environment hash describing the request. It returns a status, headers, and a body that can be iterated. This lets servers and frameworks work through a shared contract.

Minimal Rack-shaped Ruby app

app = ->(env) {
  [200,
   { "content-type" => "text/plain" },
   ["Hello from a Ruby process"]]
}

The server handles network I/O; the app supplies a response.

This is a minimal illustrative Rack response. Real applications must follow body and header rules and close resources when required. Rack middleware wraps another app and can inspect or alter the incoming environment or outgoing result. An early middleware response can bypass the Rails router entirely.

Concurrency means work can overlap.

Puma can use threads and worker processes. Threads can overlap waits for I/O. In common CRuby, the Global VM Lock limits parallel execution of Ruby code within a process.

Concurrency
Several requests are in progress, including some waiting on I/O.
Parallelism
Several pieces of work execute simultaneously on different cores.

CRuby can release the GVL during many blocking operations, and native extensions can behave differently. Multiple worker processes can execute Ruby in parallel. More workers consume more memory; more threads need adequate database connections and thread-safe code. The optimal configuration depends on the workload and limits.

The same program can return HTML, JSON, or a file.

A dynamic response is computed for the request. A static response can reuse existing bytes. An API is an interface for other programs; it still uses the same network underneath.

HTML response
A document the browser can render directly.
JSON response
Structured data a client program interprets.

Server-side rendering, client-side rendering, and hybrid approaches divide work differently. A Rails app can render HTML, expose JSON, or do both. Choosing JSON does not remove the need for authentication, authorization, validation, or persistence. Choosing HTML does not prevent rich interactive behavior.

Sources: Rails on Rack, Puma architecture, Rack specification

Enough Ruby to read Rails

Make the code stop looking like punctuation.

Variables give names to values.

Ruby is the programming language. Rails is a framework written in Ruby. A variable refers to an object, and a method call asks an object to do something.

Ruby, running on the server

title = "First note"
count = 3

title.upcase   # => "FIRST NOTE"
count + 1      # => 4

The # character begins a comment; => in these comments shows the result.

Ruby is dynamically typed: objects have classes, but a variable is not fixed to one declared type. Assignment changes what a variable refers to. Some operations return a new object; others mutate an existing object. That difference matters when several references point to the same object.

Arrays keep sequences. Hashes map keys to values.

An array groups ordered values. A hash associates keys with values. Symbols such as :title are commonly used as names or identifiers in Ruby code.

Ruby collections

titles = ["Read", "Build", "Ship"]
titles.first                  # => "Read"

note = { title: "Read", pinned: true }
note[:title]                  # => "Read"

{ title: "Read" } uses a symbol key; it is not a variable assignment.

A plain Ruby hash distinguishes the string "title" from the symbol :title. Rails parameter and indifferent-access objects can accept both, which is a Rails behavior, not a universal property of hashes. JSON object keys are strings. Arrays are zero-indexed: titles[0] retrieves the first element.

Methods name behavior.

A method takes inputs and returns a result. Ruby usually returns its final expression. Parentheses are often optional, which makes Rails declarations look less like ordinary method calls.

Ruby methods

def label(title, prefix: "Note")
  "#{prefix}: #{title}"
end

label("Read")                 # => "Note: Read"
label("Read", prefix: "Idea") # => "Idea: Read"

#{...} interpolates a Ruby expression into a double-quoted string.

prefix: is a keyword argument. Return can exit explicitly, but is not required for the last expression. In Rails, has_many :notes and validates :title, presence: true are method calls executed while defining a class. They are not extra syntax built into the Ruby language.

A class describes objects and their behavior.

An object holds state and responds to methods. A class defines shared behavior for its instances. An instance variable beginning with @ belongs to one object.

Plain Ruby, not yet Active Record

class Draft
  def initialize(title)
    @title = title
  end

  def label
    "Draft: #{@title}"
  end
end

Draft.new("Read").label # => "Draft: Read"

new constructs an instance and invokes initialize. A local variable belongs to its local scope; @title belongs to the instance. self means the current receiver. Methods defined with def self.name are methods on the class object, often called class methods. This plain Draft does not save anything to a database.

Inheritance and modules share behavior in different ways.

A subclass inherits behavior from a parent. A module groups reusable methods or names. Rails uses both: your model inherits from ApplicationRecord, while concerns can mix in shared behavior.

Ruby structure

class Note < ApplicationRecord
  include Searchable
end

module Searchable
  # Shared behavior can live here.
end

In real files the module must be available when included; Rails autoloading can resolve it.

Inheritance expresses a relationship in the object model, not automatically a new database table. Rails single-table inheritance is a particular persistence convention with its own rules. include adds a module’s instance methods; extend adds methods to the receiving object. A concern should capture a coherent shared responsibility, not merely hide a long file.

A block lets a method receive a little piece of behavior.

Enumerable methods can apply a block to each element. Change the collection rule below and inspect the corresponding Ruby expression and result.

The lab computes the shown collection operation in JavaScript; it is not a Ruby interpreter. Ruby blocks use do…end or braces. map returns transformed elements, select retains elements matching a condition, and each iterates primarily for side effects. Active Record relations can resemble arrays while representing a database query; where is not just select with a different spelling.

Nil, false, and failure mean different things.

nil represents absence. Only nil and false are falsey in Ruby; zero and an empty string are truthy. Exceptions interrupt normal flow until handled.

Ruby edge cases

if 0
  puts "This runs"
end

note = nil
note&.title  # => nil

Note.find(999) # may raise RecordNotFound

&. is safe navigation; it skips the call when the receiver is nil.

Do not rescue every exception and pretend success: that hides failures. Active Record find raises if the record does not exist; find_by returns nil. save commonly returns false for validation failure, while save! raises. These are deliberate API distinctions; inspect which contract the caller needs.

Gems bring libraries. Bundler makes their versions reproducible.

The Gemfile declares dependencies. Gemfile.lock records a resolved set of versions. Bundler installs and activates compatible dependencies so your code runs against an intentional set.

  1. Gemfile: requirements
  2. Resolve dependencies
  3. Gemfile.lock: selected versions
  4. bundle exec: selected environment

A gem is a Ruby package. Rails itself is composed of gems such as activerecord and actionpack. Locking versions does not eliminate vulnerabilities; updates and compatibility checks remain necessary. bin/rails is the application’s command wrapper. Different Ruby versions can also change behavior, so pin and document the runtime as well.

Sources: Ruby quickstart, Ruby syntax, Bundler rationale

Rails conventions

Less wiring because the names agree.

Rails organizes a recurring problem.

Most web apps receive input, apply rules, read or write data, and return a representation. Rails provides conventions and cooperating libraries for those jobs.

Model
Data access and domain behavior.
View
A representation, often HTML.
Controller
Coordinates the request, checks access, and chooses a response.

MVC means Model–View–Controller. It is a separation of responsibilities, not a law that every operation needs exactly three files. A model is more than a database table, and not every model must use Active Record. Keep business rules somewhere reusable rather than copying them into controllers and views.

The directory is a map of responsibilities.

When you know what kind of change you need, convention tells you where to look. These paths are part of the interface Rails gives the developer.

Inside a Rails application

config/routes.rb                 URL → action
app/controllers/notes_controller.rb
app/models/note.rb
app/views/notes/show.html.erb
db/migrate/                      schema changes
test/                            checks
config/environments/             runtime settings

Other common directories include app/jobs, app/mailers, app/helpers, app/assets, app/javascript, and storage. config/database.yml describes database connections; credentials and environment variables carry sensitive configuration under an explicit policy. public holds files that may be served directly.

Names replace a lot of manual wiring.

A Note class conventionally maps to the notes table. NotesController handles note actions. The file app/models/note.rb defines Note. Zeitwerk uses paths to find constants.

  1. note.rb
  2. Note
  3. notes table
  4. notes/show.html.erb

Autoloading locates constants when needed. Development reloading lets changed source be used without a full manual restart in common cases. Production typically eager-loads application code. Naming and directory consistency matter; a file defining the wrong constant can fail to load. Rails inflections can be customized for irregular names.

Development and production are different environments.

Development favors fast feedback. Test isolates repeatable checks. Production favors performance, stable configuration, and appropriate error handling. Configuration is part of the application’s behavior.

Development / test
Reload code, expose useful errors, isolate test data.
Production
Load code predictably, protect secrets, report errors safely.

A secret committed to source control is no longer secret merely because the repository is private. Rails encrypted credentials require a decryption key kept separately. Environment variables are another configuration channel, not inherently a complete secrets-management system. Never show detailed production errors or sensitive request parameters to everyone.

A route matches a verb and a path.

resources :notes expands a conventional resource into routes. The path alone is not enough: GET /notes and POST /notes mean different operations.

config/routes.rb

Rails.application.routes.draw do
  resources :notes
  root "notes#index"
end

# GET /notes/7   → notes#show
# POST /notes    → notes#create
# PATCH /notes/7 → notes#update

Routes are generally matched in declaration order. Named route helpers such as note_path(note) construct paths consistently. Nested routes express context, but do not automatically enforce ownership. Restrict routes with only or except when an app does not implement every action.

Generators write files. They do not hide the implementation.

A generator creates an editable starting point. The Rails console lets you inspect objects and query the app. Commands for routes, migrations, and tests expose the framework’s moving parts.

Commands in an app directory

bin/rails generate model Note title:string user:references
bin/rails db:migrate
bin/rails routes
bin/rails console
bin/rails test

A generated model is only a starting point; decide validations, constraints, and access rules.

A console connected to production is real application code with real side effects. Use it deliberately. Migrations are versioned schema changes; editing an old applied migration does not magically update deployed databases. Rake tasks and bin/rails commands automate application work. Smaller explicit changes are easier to understand than unexplored generated scaffolding.

Sources: Getting started, Autoloading, Routing, Configuration

A request through Rails

Watch one note cross the application.

Start at the router. End at a response.

Change the request and submit it. The trace shows which boundaries it crosses. An invalid title never reaches the write; a missing route never reaches the controller.

This is a JavaScript simulation of a small Rails controller contract. It does not execute Ruby or run a Rails server. User 1 owns note 7 in the model. The lab deliberately distinguishes routing, login, CSRF, scoped lookup, validation, persistence, and redirects. Example errors are illustrative; exact application responses depend on its controllers and middleware.

One title becomes several representations.

Follow Read the web through the same save. Edit the title and inspect each representation. It remains data even though each system gives it a different shape.

The form field name note[title] causes Rails to build nested params. Strong parameters allow title; the authenticated association supplies user_id. Active Record binds values to SQL. The response escapes the title for HTML. The model demonstrates these transformations without running Ruby or a database. Browser HTML parsing then turns escaped character references back into displayed text.

Params are input, not permission.

Rails collects route values, query fields, and body fields into params. Strong parameters select allowed attributes. They do not decide which records the user may edit.

Inside NotesController

def note_params
  params.expect(note: [:title])
end

Rails 8.1 style: require the expected structure and permit only title.

A traditional equivalent for this simple shape is params.require(:note).permit(:title). Never allow user_id merely because a form submitted it. Derive ownership from the authenticated user. Strong parameters protect mass assignment; they do not sanitize all content or replace validation and authorization. A missing required structure can become a 400 response.

The controller coordinates the decision.

Build the note through the current user. Save it. Choose the response according to the result. The controller connects the HTTP interaction to domain behavior.

app/controllers/notes_controller.rb

def create
  @note = current_user.notes.build(note_params)
  if @note.save
    redirect_to @note, status: :see_other
  else
    render :new, status: :unprocessable_entity
  end
end

Assumes authentication has established current_user; see the security chapter.

current_user is an application-level helper, not a universal automatically available Rails method. Rails’ authentication generator uses its own generated conventions, including Current.user; adapt consistently. The example assumes an authenticated User has_many :notes and Note belongs_to :user. A database failure is not identical to an ordinary validation failure.

A model query returns application objects.

A scoped lookup can ensure the record belongs to the current user. Active Record turns the query into SQL and turns the result into a Ruby object.

A show action

def show
  @note = current_user.notes.find(params[:id])
end

# Conceptually:
# SELECT ... FROM notes
# WHERE user_id = ? AND id = ? LIMIT 1

The bound values come from the authenticated user and the requested ID.

A record outside this scope is not found even if it exists for somebody else. This is a useful authorization pattern, but more complex sharing rules need an explicit policy. An instance variable such as @note exposes the object to the view for this request; it is not shared permanent state across users.

The template turns values into a document.

Rails renders the view with data from the controller. Embedded Ruby—ERB—can evaluate expressions and insert their escaped output into HTML.

app/views/notes/show.html.erb

<h1><%= @note.title %></h1>
<%= link_to "Edit", edit_note_path(@note) %>
<%= link_to "All notes", notes_path %>

The browser receives the resulting HTML, not these Ruby expressions.

A controller action can render implicitly by convention, as show commonly does. The template runs on the server. A layout wraps its output with shared page structure. Escaping must match the output context; marking arbitrary user input html_safe bypasses protection and can introduce XSS.

A failed save should keep the user’s input.

When validation fails, render the form with the unsaved object and its errors. The database remains unchanged. The user gets a chance to fix the title.

app/models/note.rb

class Note < ApplicationRecord
  belongs_to :user
  validates :title, presence: true, length: { maximum: 100 }
end

The database also needs appropriate ownership and null constraints.

Rendering new does not run the new controller action. The create action must supply whatever the template needs. Active Record validations populate errors. Database constraints are a separate line of protection; validations can be skipped by some methods and cannot alone prevent concurrent uniqueness races.

Render answers now. Redirect asks the browser to ask again.

After a successful form submission, a 303 redirect commonly leads to a GET of the saved resource. Refreshing that page then repeats the GET instead of the original POST.

render :new
Same request; return a form and validation errors.
redirect_to @note
Return Location; browser makes a new request.

This is the Post/Redirect/Get pattern. redirect_to sets a response but does not necessarily stop Ruby execution; avoid unintended code after it or return when appropriate. Flash messages carry short-lived information across requests under the app’s session setup. A redirect does not share the original action’s local variables with the next action.

CRUD is a useful vocabulary, not the whole domain.

Create, read, update, and delete describe common data operations. Real actions such as publish or invite may involve additional rules, side effects, or several records.

HTML flow
Submit form → validate → redirect or render errors.
API flow
Submit JSON → validate → return resource or structured errors.

An API create might return 201 with a Location header; a destroy might return 204. Choose a consistent contract. API-only Rails apps omit some browser-oriented middleware by default and need an intentional authentication strategy. JSON input still needs shape checks, permitted fields, authorization, and rate limits.

Sources: Controllers, Routing, Layouts and rendering, Form helpers

Data that survives

Ruby objects meet a database.

A database keeps shared state beyond one process.

A relational database stores rows in tables. Columns define attributes. A primary key identifies each row. A foreign key can require an association to reference an existing row.

Two related tables

users                       notes
id | email                  id | user_id | title
1  | [email protected]     7  | 1       | Read
2  | [email protected]      8  | 2       | Build

notes.user_id references users.id.

Persistence depends on database durability settings, storage, and recovery design. The database is itself a server or embedded engine, not simply “a file Ruby reads.” SQLite is embedded; PostgreSQL is commonly a separate server. Rails can use either, but concurrency and operational details differ.

SQL describes the data operation.

Structured Query Language lets you select, insert, update, and delete rows. A query describes the result wanted; the database planner chooses a way to execute it.

SQL in the database

SELECT id, title FROM notes WHERE user_id = 1;
INSERT INTO notes (user_id, title, created_at, updated_at)
  VALUES (1, 'Read', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP);
UPDATE notes SET title = 'Read more',
  updated_at = CURRENT_TIMESTAMP WHERE id = 7;
DELETE FROM notes WHERE id = 7;

Production application code should bind untrusted values, not interpolate them into SQL.

ORDER BY is necessary when result order matters. LIMIT bounds the rows returned, not automatically all the work performed. NULL represents missing or unknown information and uses three-valued logic: compare with IS NULL rather than = NULL. The exact SQL dialect and available features depend on the database.

Active Record maps between rows and Ruby objects.

A model exposes domain behavior around persisted attributes. A relation describes a query that can be refined before it is executed.

Ruby → query → objects

notes = Note.where(user_id: 1)
notes = notes.order(created_at: :desc).limit(10)

notes.each { |note| puts note.title }

Building the relation commonly defers its SELECT until the results are needed.

find retrieves one record by primary key or raises. pluck can retrieve raw attribute values without building full model objects. count may issue an aggregate query; size can use already loaded data or a query depending on state. update_all and delete_all bypass normal object callbacks and validations, so use them intentionally.

A migration changes the shape of stored data.

Migrations are ordered, versioned steps. Applying one changes the database schema. Your Ruby class and your deployed database must agree about that schema.

A Rails migration

class CreateNotes < ActiveRecord::Migration[8.1]
  def change
    create_table :notes do |t|
      t.references :user, null: false, foreign_key: true
      t.string :title, null: false
      t.timestamps
    end
  end
end

Create users first. A NOT NULL constraint does not reject an empty string.

schema.rb or structure.sql records a schema snapshot. Migrations can alter tables, indexes, and data, but large operations can lock tables or take a long time. Some operations are not automatically reversible. In a rolling deployment, old and new app versions may run simultaneously, so expand the schema compatibly before removing old fields.

Associations express relationships; joins combine rows.

A user has many notes. A note belongs to a user. These declarations give convenient methods, while the foreign key and database constraints govern stored references.

Related models

class User < ApplicationRecord
  has_many :notes, dependent: :destroy
end

class Note < ApplicationRecord
  belongs_to :user
end

user.notes.where("created_at >= ?", 1.week.ago) queries recent notes owned by that user.

has_many :through models many-to-many relationships with an explicit join model. belongs_to normally expects the foreign key on its own table. dependent: :destroy runs destruction callbacks for associated objects and may be expensive; database cascading is a separate mechanism. Association declarations do not automatically install every database constraint you need.

A JOIN follows the stored relationship.

The foreign key lets SQL match a note to its owner. Change the selected user and compare the two input tables with the joined result. The query combines rows; it does not merge the tables permanently.

An INNER JOIN retains matching pairs. A LEFT JOIN also retains rows from the left side with no match, filling right-side fields with NULL. Joining one user to many notes produces repeated user fields in multiple result rows. Aggregates such as COUNT can summarize groups. In Active Record, joins helps filter across associations; preloading is separately concerned with avoiding later queries.

Friendly validation and hard constraints have different jobs.

A Rails validation can explain an error before writing. A database constraint protects stored truth even when another process, a bulk operation, or concurrent requests bypass that validation.

Application validation
“Please provide a title.” Useful feedback around a model operation.
Database constraint
“A note must reference a real user.” Enforced on writes by the database.

For uniqueness, pair the user-friendly model validation with a matching unique database index or constraint. Scope and case rules must agree. A race can still produce a database exception after validation passes; handle the intended conflict. NOT NULL, CHECK, UNIQUE, and FOREIGN KEY protect different invariants.

An index trades storage and write work for a faster lookup.

Without a useful index, the database may scan many rows. A suitable index can narrow the search. Increase the table size and compare the teaching model’s lookup work.

The model compares N scanned row slots against approximately log2(N) comparisons for a single-key tree lookup. Real B-tree indexes have pages with many keys; planners consider selectivity, caching, I/O, row fetches, and ordering. Indexes consume space and must be maintained on writes. EXPLAIN shows a plan; EXPLAIN ANALYZE executes and measures the query, so use it carefully.

One page can accidentally cause many queries.

Load a list of notes, then fetch each author one at a time: one list query plus N author lookups. Eager loading can fetch the related records together.

The lab models one query for notes plus one per author access, versus two queries with separate eager loading. Real Rails includes may use separate queries or a join depending on the relation. Joins for filtering do not automatically guarantee that later association accesses are preloaded. Measure query count, returned rows, memory, and latency together.

A model can express a domain action.

Do not make every caller repeat the rules for changing a note. Give a coherent operation a name on the model. This keeps behavior close to the state it governs.

app/models/note.rb

def rename_to(new_title)
  update!(title: new_title.strip)
end

note.rename_to(" Read ") stores "Read" or raises if validation fails.

A model method is ordinary Ruby. It can coordinate attributes and collaborators, but should not secretly depend on a controller’s params or current user. Authorization still belongs at the appropriate boundary. A model need not inherit Active Record: Active Model can give a plain Ruby object naming, validation, and form integration without a database row.

A scope gives a recurring query a name.

A scope composes a relation. You can combine it with ownership, ordering, and limits before loading rows. The time calculation belongs inside the lambda so it is reevaluated when called.

app/models/note.rb

scope :recent, -> {
  where("created_at >= ?", 1.week.ago)
}

# At a call site:
current_user.notes.recent.order(created_at: :desc)

A scope describes a query; it does not itself grant access to another user’s notes.

Active Support supplies helpers such as 1.week.ago and time-zone-aware utilities. A scope should be used when it clarifies a meaningful query; complicated logic can be a class method returning a relation. Be cautious with default_scope: an invisible global filter can surprise maintenance tasks and association behavior.

Save has a lifecycle, and rollback changes what should happen next.

Validation, callbacks, and database writes occur in a defined sequence. Change the outcome. Notice why an external side effect belongs after a successful commit, not merely after a row was written.

This is a simplified create lifecycle. Rails has distinct validation, save, create/update, destroy, and transaction callbacks. A normal save wraps its lifecycle in a transaction, but an enclosing transaction can postpone the final commit. after_create_commit runs after the outer transaction commits. If it fails, the earlier database write is not rolled back. For reliably coordinating external work, consider durable intent such as an outbox.

Callbacks are useful when their timing is part of the rule.

A callback attaches behavior to the persistence lifecycle. Keep it small and predictable. A workflow that has several named steps is often clearer as an explicit method than as hidden chains of callbacks.

A small model callback

before_validation :normalize_title

private

def normalize_title
  self.title = title&.strip
end

self.title= calls the attribute writer; a bare title= would assign a local variable.

This example normalizes input before validating it. Some bulk write methods skip callbacks and validations. after_save does not mean the surrounding transaction is already committed. Concerns can package cohesive shared behavior into a module; they do not change transaction boundaries or excuse unclear dependencies.

Sources: Active Record, Migrations, Associations, Queries, PostgreSQL indexes

When requests collide

Correct alone is not always correct together.

Several writes can form one database operation.

A transaction groups work so it can commit together or roll back together. If creating a note and its required metadata must succeed as a unit, put them in the same transaction.

  1. Begin transaction
  2. Write note
  3. Write metadata
  4. Commit both — or roll back

ACID stands for atomicity, consistency, isolation, and durability. Consistency means preserving declared and application-maintained invariants, not a promise that arbitrary code is correct. Isolation levels differ; durability depends on database configuration and failure assumptions. A database transaction does not automatically roll back an email or external payment.

Two correct-looking requests can lose an update.

Both shoppers read “one left.” Both try to buy. Interleave their operations, then change the strategy. Watch which rule protects the final item.

The unsafe model reads a stock value into each request and writes its locally computed result. The atomic model performs a conditional decrement only when stock is positive, within the database operation. A real purchase also needs its order record and inventory change to be coordinated transactionally. This model isolates just the stock invariant.

Protect the read-modify-write decision.

Use an atomic database operation when possible. For a more complex decision, lock the relevant row in a transaction. Optimistic locking detects that another write changed the version.

Conceptual SQL for reserving one item

UPDATE products
SET stock = stock - 1
WHERE id = ? AND stock > 0;

-- Check that exactly one row changed.

Zero affected rows means this operation did not reserve an item.

Rails with_lock can acquire a row lock inside a transaction. Optimistic locking commonly uses a lock_version column and raises when the stored version no longer matches. Neither technique automatically covers unrelated rows or an external service. Locks must be held briefly and acquired consistently to reduce contention and deadlock risk.

Put the whole local invariant inside the transaction.

For two related database changes, group the operation and use raising methods so a failed step aborts the group. Rescue a failure outside the transaction when deciding how to report it.

Ruby / Active Record

Note.transaction do
  note = user.notes.create!(title: "Read")
  AuditEntry.create!(note: note, event: "created")
end

Illustrative second model: AuditEntry must have its own schema and validation.

If the audit row is mandatory and its creation fails, the note insertion rolls back. This assumes both models participate in the same database transaction. Separate databases and external services are not automatically included. A save returning false does not itself raise and roll back an enclosing transaction; that is why the bang methods matter in this example.

“I checked and it was free” can become false before the write.

Two requests can both pass a uniqueness validation before either inserts. A unique database constraint is the boundary that can arbitrate the conflicting writes.

  1. A: name available
  2. B: name available
  3. A: insert succeeds
  4. B: unique constraint rejects

The application should recognize the intended conflict and return useful feedback or retry with a different value where appropriate. Do not catch every database error as “duplicate.” A scoped uniqueness rule, such as title per user, needs a matching compound unique index. Nullable values and case sensitivity can change uniqueness semantics by database.

Isolation determines what concurrent work can observe.

A database may give each statement or transaction a snapshot. Stronger isolation can prevent more anomalies, but conflicting work may block or need a retry.

Read committed
In PostgreSQL, each statement sees committed data as of its start.
Serializable
Committed transactions behave as if ordered; some attempts must retry.

MVCC—multiversion concurrency control—retains versions so readers and writers can overlap. Repeatable read and serializable are not interchangeable. Deadlocks can arise when transactions wait for each other’s locks; the database aborts one. Retry the entire appropriate transaction with bounds, not just an arbitrary final statement. SQLite’s concurrency model differs from PostgreSQL’s.

A timeout does not tell you whether the write happened.

The server might commit, then lose the response. Retrying can repeat a side effect. An idempotency key gives repeated attempts one operation identity.

  1. Request with key K
  2. Record key + outcome atomically
  3. Response lost
  4. Retry K → recover prior outcome

Exactly-once effects require deliberate coordination, not a slogan from a queue library. For a database change plus a message, a transactional outbox records the intended message in the same database transaction; a worker delivers it with retry and deduplication. after_commit avoids sending before rollback, but by itself does not close the crash gap between commit and enqueue.

Sources: PostgreSQL transactions, PostgreSQL isolation, Queries and locking, Callbacks

HTML from Rails

Keep the browser’s strengths.

ERB runs before the response leaves the server.

<%= ... %> inserts an expression’s output. <% ... %> runs Ruby without inserting that expression directly. Escaping helps keep a title as text instead of executable markup.

A view template

<ul>
  <% @notes.each do |note| %>
    <li><%= note.title %></li>
  <% end %>
</ul>

A title containing <script> should be displayed as text, not executed.

HTML escaping is not a universal sanitizer for every possible JavaScript, CSS, or URL context. Avoid injecting untrusted content into executable contexts. raw and html_safe explicitly bypass escaping; only use them when the content is safe for the exact context. Rich text needs a deliberate sanitization policy.

Layouts share the page shell. Partials share a piece.

A layout holds common structure such as the document head and navigation. A partial can render one note. Helpers express small presentation operations.

Layout and partial conventions

<!-- layouts/application.html.erb -->
<main><%= yield %></main>

<!-- notes/index.html.erb -->
<%= render @notes %>

<!-- notes/_note.html.erb -->
<article><%= note.title %></article>

Here yield inserts the action’s rendered content into the layout. Rendering a collection conventionally chooses a partial for each object. Locals make dependencies clearer than reaching for many unrelated instance variables. Avoid turning helpers into hidden database-query engines; view rendering can otherwise trigger surprising work.

A Rails form is still an HTML form.

form_with generates names and destinations from model conventions. Rails includes CSRF protection fields and can represent non-GET/POST methods through method override.

app/views/notes/_form.html.erb

<%= form_with model: note do |form| %>
  <%= form.label :title %>
  <%= form.text_field :title %>
  <%= form.submit "Save" %>
<% end %>

Fields named note[title] become nested request parameters.

Native HTML form methods are GET and POST. Rails commonly uses a hidden _method field for PATCH or DELETE semantics, interpreted by middleware. The authenticity token helps protect state-changing requests. A disabled button or hidden field is not a permission check; the server must still enforce access.

Assets are a different pipeline from model data.

Stylesheets, JavaScript, images, and fonts are static assets. Rails 8 uses Propshaft by default for asset organization and fingerprinting. JavaScript can use import maps or a bundling setup.

  1. Source assets
  2. Resolve / build as configured
  3. Fingerprint files
  4. HTML references asset URLs

Propshaft is not a general transpiler or full JavaScript bundler. Import maps map module names to URLs and let browsers load modules without a bundling step. Build tools can compile or bundle when the project needs them. Development and production serving differ; verify deployed assets rather than assuming a working development page proves the build is complete.

Turbo can replace HTML without replacing your whole programming model.

Turbo Drive accelerates navigation. Frames target a region. Streams apply named changes to the DOM. Try the same result with each response shape.

This local simulation shows response scope, not a full implementation of Turbo navigation, caching, focus, or history. Frames expect matching frame structure. Streams can arrive through a form response or a live connection. Stream actions include append, prepend, replace, update, remove, and others. The server still authorizes every request and subscription.

Stimulus gives existing HTML small pieces of behavior.

A Stimulus controller connects JavaScript to HTML through attributes. Targets identify elements; actions connect events to methods. The HTML can remain useful before the enhancement connects.

HTML + JavaScript convention

<div data-controller="counter">
  <button data-action="counter#increment">Add</button>
  <span data-counter-target="value">0</span>
</div>

The counter controller supplies increment and updates its value target.

Stimulus is for behavior attached to the DOM, not a replacement for authorization or database rules. A server-rendered app can still contain a client-heavy island when needed. Progressive enhancement means the simpler baseline works and enhancements add capabilities without needlessly making every operation depend on a large client runtime.

Language and time zones are application data too.

Internationalization separates user-facing messages from code. A user’s time zone changes how an instant should be displayed. Store and compare time deliberately, then localize it at the presentation boundary.

Rails helpers

I18n.t("notes.created")
Time.current

# In a view, with translations configured:
l(@note.created_at, format: :short)

Translation keys need entries in config/locales; l localizes a value.

Do not concatenate translated sentence fragments; word order and plural rules vary. UTC instants and local calendar dates are different concepts. A meeting time, a birthday, and “tomorrow at nine” need different models. Daylight-saving transitions make some local times nonexistent or ambiguous. Rails Time.zone and Active Support help, but the domain must define the intended meaning.

Sources: Action View, Form helpers, Assets, Turbo handbook, Stimulus handbook

Who can do what?

The browser is not a trusted witness.

A cookie can carry continuity between requests.

The server sends Set-Cookie. The browser stores the cookie and includes it on matching later requests. Rails can use this to associate requests with session state.

  1. Login response: Set-Cookie
  2. Browser stores cookie
  3. Next request: Cookie
  4. Server recovers session

Rails’ default CookieStore stores encrypted, signed session data in the browser. Other designs store only a session identifier there and keep data server-side. The Rails authentication generator uses its own persisted-session pattern. Cookies are bounded in size. Secure restricts sending to secure connections; HttpOnly prevents ordinary script access; SameSite influences cross-site sending.

Authentication establishes an identity.

A login flow verifies a credential and creates a session. Passwords should be stored as slow, salted password hashes, not recoverable plaintext. Sessions need expiration and revocation behavior.

Credential check
Verify the supplied secret against a password hash.
Session continuity
Issue and later verify a session credential so users need not retype it.

Rails has_secure_password integrates bcrypt when configured; its authentication generator provides a starting flow. Tune and maintain password hashing using appropriate guidance. Reset flows, session fixation, account enumeration, credential stuffing, multi-factor authentication, and OAuth/OIDC integration add their own requirements. OAuth is authorization delegation; OpenID Connect adds an identity layer.

Knowing who you are does not decide what you may access.

Authentication says “this is user 2.” Authorization asks “may user 2 edit note 7?” Test ownership in the request lab. Changing an ID in the URL must not bypass that check.

The model distinguishes login from an ownership rule. In a real app, enforce policy for reads, writes, downloads, and realtime subscriptions. Scoping a query to current_user.notes is a simple ownership policy. Hiding an Edit button only changes the interface; an attacker or another client can still send the HTTP request.

The browser may send a cookie on a request you did not intend.

A malicious site can try to cause a logged-in browser to submit to another site. Cross-site request forgery exploits automatically attached credentials. Rails authenticity tokens help reject forged state-changing requests.

  1. Attacker-controlled page
  2. Victim’s browser sends request
  3. Session cookie may accompany it
  4. Server checks CSRF defenses

SameSite cookies reduce many cross-site attacks but are not a complete substitute for the application’s CSRF design. GET should not perform user-requested mutations. CORS governs reading responses, not all sending of requests. APIs using bearer tokens outside automatic cookie attachment have a different threat model; do not simply disable protections because the response is JSON.

XSS makes untrusted content act as code.

Cross-site scripting lets injected script run with the page’s authority. Escaping and safe DOM APIs keep text as text. A Content Security Policy can add defense in depth.

Safer text insertion
element.textContent = title
Dangerous with untrusted markup
element.innerHTML = title

HttpOnly can prevent JavaScript from reading a cookie, but an XSS payload may still issue actions using the victim’s active session. CSP does not replace correct escaping. Validate URLs and sanitize intentionally supported rich HTML. Treat stored content and third-party data as untrusted, even when they came from your own database.

SQL values must stay values.

Parameterized queries send query structure separately from bound values. Interpolating raw user input into SQL can let that input alter the query’s meaning.

Ruby query contrast

Note.where("title = ?", params[:title])
# Binds the title as data.

# Avoid constructing SQL by concatenating input.

Active Record hash conditions also bind values for common queries.

Binding values does not automatically make arbitrary table names, column names, sort expressions, or SQL fragments safe. Select those from an allowlist when clients influence them. Database roles should have appropriate privileges. Input validation supports domain rules; it is not a substitute for safe query construction.

Trust boundaries exist beyond the login page.

File uploads, external URLs, administrative actions, webhooks, logs, and secrets all cross boundaries. Decide what each input is allowed to cause before passing it onward.

Inbound
Authorize, validate shape and size, verify webhook signatures, rate-limit abuse.
Outbound
Restrict external fetch destinations, redact logs, protect credentials and private files.

Server-side request forgery can make a server fetch internal resources on an attacker’s behalf. Uploads can contain unsafe content or consume resources. Signed links and webhook signatures need expiry or replay policies appropriate to the use case. Dependency scanning and security updates complement application checks. These are areas for deeper study, not a claim that one checklist proves security.

Sources: Rails security, OWASP authorization, OWASP password storage

After the response

Some work should outlive a request.

A job separates acceptance from completion.

The request can enqueue work and respond. A worker later performs it. Active Job supplies the interface; a queue backend stores and dispatches jobs. Rails 8 uses Solid Queue by default.

  1. Request enqueues
  2. Queue stores work
  3. Worker claims job
  4. Work succeeds or retries

A job payload should carry stable identifiers and necessary small inputs, not assume an in-memory object will survive. The record may change or disappear before execution. Queue durability, scheduling, priority, concurrency, and retries depend on the backend and configuration. Returning “queued” is not evidence that an email has been delivered.

A crash can happen after the side effect.

The worker sends a message, then crashes before recording completion. Retrying is sensible—but might send twice. Toggle deduplication and run the failure scenario.

The deduplicated model assumes an external provider that honors a durable idempotency key for the operation. A local “already sent” flag alone cannot atomically coordinate with an arbitrary email provider. Provider time windows and guarantees matter. Outbox and inbox patterns help coordinate durable intent and deduplication; no universal queue setting makes all side effects exactly once.

Mail has an outgoing and an incoming side.

Action Mailer builds messages; delivery can happen through a background job. Action Mailbox routes incoming messages into the application after an email service receives them.

Rails mail delivery

NoteMailer.with(note: @note).created.deliver_later

The mailer action builds the message; a job performs delivery.

Email submission to a provider is not proof it reached a recipient’s inbox. Bounces, retries, suppression, DNS configuration, and reputation affect delivery. Avoid assuming a job can read a request’s transient state. Tests can check message composition and enqueue behavior without sending real email.

Uploaded bytes usually live outside the relational row.

Active Storage connects database metadata to stored files. Action Text adds rich text editing and storage conventions. Both still require access rules and resource limits.

  1. Browser uploads bytes
  2. Storage service keeps file
  3. Database records attachment
  4. App authorizes later access

Direct uploads can send bytes to storage without proxying them through Rails. The application still needs to associate the completed upload and enforce permissions. A signed URL may be usable by anyone who possesses it until expiry. Image transformations and previews can consume CPU and need limits. Back up blobs as well as database metadata.

Realtime means keeping a path open or checking repeatedly.

Polling asks for updates repeatedly. SSE streams events from server to client. WebSocket supports messages both ways. Action Cable integrates WebSocket connections and channels with Rails.

Polling / SSE
Repeated requests, or a server-to-client HTTP event stream.
Action Cable
Connections subscribe to authorized channels; broadcasts reach subscribers.

A broadcast is not durable history unless you store it. Reconnecting clients may need to fetch missed state. Authorize both connection identity and channel subscriptions. Multiple app processes need a compatible shared subscription adapter. Slow clients and fan-out create backpressure and capacity concerns.

Background work needs its own visibility.

A fast web response can hide a stuck queue. Measure queue age, attempts, failures, and completion. Scheduled jobs also need a policy for overlap and missed runs.

Request health
Latency, errors, and throughput.
Worker health
Oldest waiting job, processing time, retries, and failed work.

Retries should distinguish transient failures from permanent invalid inputs and use bounded backoff where appropriate. A recurring job should be safe if it overlaps or runs twice. Callbacks can enqueue side effects after commit, but complicated workflows deserve explicit control flow. Cancellation and graceful shutdown must leave work recoverable.

Sources: Active Job, Action Mailer, Active Storage, Action Cable, Action Text

Keeping it running

A working feature meets time and traffic.

Deployment makes a version run somewhere real.

Build the application and assets, supply configuration, prepare the database, and start healthy processes behind the traffic entry point. A container packages a runtime; it does not eliminate these jobs.

  1. Source + dependencies
  2. Build artifact
  3. Configure secrets
  4. Compatible migrations
  5. Healthy app receives traffic

Kamal can deploy containerized applications to servers; other deployment systems make different tradeoffs. A container shares the host kernel, while a virtual machine includes a separate guest kernel. Build artifacts should be reproducible enough to identify and roll back a version. Avoid compiling a different dependency set accidentally on each server.

Booting is not the same as being ready.

A process can exist before it can serve requests. Health checks and graceful shutdown help direct traffic only to ready instances and let in-flight work finish during replacement.

  1. Start
  2. Initialize
  3. Readiness passes
  4. Receive traffic
  5. Drain before shutdown

A liveness check asks whether the process should be restarted; readiness asks whether it should receive traffic. A dependency outage should not necessarily cause every app process to restart in a loop. Proxies need sensible timeouts and trusted forwarding-header configuration. HTTPS URLs, secure cookies, and asset hosts must match the deployment.

Your capacity is limited by the narrowest stage.

Increase web workers in the model. If database capacity is lower, the extra requests wait there. More concurrency can create a larger queue without increasing completed work.

The lab is a steady-state capacity estimate, not a load test or a detailed queueing simulation. It compares arrival rate with web slots divided by service time and database slots divided by database time. Near saturation, real tail latency can grow sharply even when averages look acceptable. CPU, memory, locks, I/O, and external services add further limits.

Scale the bottleneck you actually measured.

Faster queries, a useful cache, or fewer round trips may beat another app server. Read replicas add capacity for some reads but can lag behind writes. Multiple writers make consistency harder.

Vertical / horizontal
Give one machine more resources, or spread work across machines.
Stateful / stateless
Shared durable state needs coordination; replaceable app workers simplify scaling.

A stateless web tier can still use sessions by storing or cryptographically carrying session state appropriately. Sticky sessions bind a client to an instance but can complicate failures. Replica lag can make a user’s new note seem to vanish if the next read goes to a lagging replica. Sharding splits data across databases and complicates joins and transactions.

Logs, metrics, and traces answer different questions.

Logs describe events. Metrics summarize behavior over time. Traces connect timed spans across components. Use a request ID to follow one failed save through proxies, Rails, queries, and jobs.

Metrics
How often? How slow? p50 versus p95/p99, errors, saturation.
Logs + traces
Which request? Which action? Where did time or failure occur?

An average can hide a painful slow tail. A 500 count alone cannot show database timeouts that the app wrongly turned into 200 responses. Filter passwords and tokens; avoid putting private note content into logs by default. Use a correlation identifier without assuming it is an authenticated identity. Alert on user-relevant symptoms as well as exhausted resources.

Tests protect contracts at different scales.

A model test exercises a rule. A request test checks routing, authorization, and response behavior. A system test drives the app through a browser. Each catches a different class of failure.

Illustrative Rails request test

test "cannot read another user’s note" do
  sign_in users(:reader)
  get note_path(notes(:owned_by_someone_else))
  assert_response :not_found
end

sign_in here is an application-specific test helper, not a built-in universal method.

Tests need meaningful assertions: a 200 alone does not prove the right record was saved. Include failure paths and ownership boundaries. Fixtures or factories prepare data; transaction cleanup and parallel tests need isolation. CI runs checks on changes, but a passing test suite is not a substitute for deploying and observing the real system.

A backup matters when you can restore it.

Keep recoverable copies of the database and uploaded files. Define how much recent data you can lose and how long recovery may take. Practice the restore process.

Recovery point objective
How much recent work can be lost?
Recovery time objective
How long until service is restored?

Snapshots, logical backups, and write-ahead-log archiving support different recovery options. Backups need retention, access control, integrity checks, and separation from the same failures that can destroy the primary. Test restoration with the appropriate app version and encryption keys. A replica is not automatically a backup: accidental deletes can replicate too.

Safe releases let old and new code overlap.

Add a compatible field, deploy code that can use it, backfill deliberately, then remove the old path after it is unused. A code rollback cannot always undo a destructive database migration.

  1. Expand schema
  2. Deploy compatible code
  3. Backfill + verify
  4. Switch behavior
  5. Contract later

Feature flags can separate deployment from exposure, but stale flags add complexity. Dependency updates need compatibility checks and security attention. Timeouts, bounded retries, backpressure, and circuit breaking help contain failures only when chosen for the operation’s semantics. Keep a practical rollback and recovery path for each change.

Sources: Deployment tuning, Testing, Error reporting, Kamal deployment, PostgreSQL backup

Follow the whole click

Now you can see what each part owes the next.

The click is a chain of specific promises.

Change one condition in the request journey. Watch where the work stops and what the browser can honestly conclude. A failure before the write differs from a lost response after it.

This deterministic model compresses a real trace into named stages. Existing connections, caches, a CDN, and different HTTP versions can remove or reorder setup work. The diagram does not claim every request contacts DNS or establishes new TLS. A response-lost scenario demonstrates an ambiguous outcome: the database may have committed even though the browser sees failure.

Find where the time goes before optimizing it.

A page’s delay combines network exchanges, server work, transfer, and browser work. Adjust the budget. See whether bandwidth, distance, or the database dominates this scenario.

The model assumes a cold HTTP/2-like connection with a DNS delay, one TCP RTT, one TLS RTT, one request/response RTT, body serialization, app work, database work, and browser work. A warm connection skips DNS and connection setup. A fresh browser-cache hit skips origin work. Real stages overlap and resource discovery creates additional requests; this is an explanatory budget, not a benchmark.

Diagnose the boundary, not the adjective.

“The website is broken” is a symptom. Pick an observation below, make a diagnosis, and compare the evidence. Sometimes the evidence narrows the search without uniquely identifying the cause.

Good troubleshooting asks for the smallest next observation that separates hypotheses: does DNS resolve, does TCP connect, does TLS validate, does the proxy reach Puma, does Rails log the request, does the SQL commit, and what did the browser render? Never assume a timeout proves the server did nothing.

A complete feature connects six kinds of decisions.

A note is not just a model or a controller. Its URL, ownership, validation, storage, response, and interface must agree. Read the coherent feature in the companion source. Open the complete feature ↗

  1. Route
  2. Authenticated scope
  3. Permitted title
  4. Model + DB rules
  5. Response
  6. Accessible form

The companion notes-feature.md includes routes, migration, models, controller, views, and request-test examples with assumptions made explicit. It is a teaching feature for an existing authenticated Rails 8.1 app, not a falsely advertised deployed Rails service. This explorable itself runs entirely in your browser.

Draw the boundary around the guarantee.

TCP confirms byte delivery, not a purchase. TLS confirms the peer under its trust model, not a good business. A database commit confirms a transaction, not an email arriving. Each layer solves a smaller problem.

Ask “what succeeded?”
Connection? Request parsing? Validation? Commit? Job? Delivery?
Ask “what can retry?”
Reading is different from charging. Know the operation identity and side effects.

This distinction is a powerful debugging and design habit. It prevents claims that “the request succeeded” from hiding the one stage that actually matters to the user. Your product should communicate the outcome it knows, including accepted-but-pending and uncertain outcomes where necessary.

Now change the system on purpose.

Make the latency mostly distance. Make the database the bottleneck. Break certificate trust. Race a write. You now have a map for asking where to intervene—and what that intervention cannot fix.

Under the application
Signals → frames → packets → transport → TLS → HTTP.
Inside and around it
Browser → Ruby → Rails → database → workers → production.

This is a broad foundation, not the end of the subject. Deeper specialties include signal processing, routing operations, cryptography, compiler and VM internals, database engine design, distributed consensus, accessibility engineering, and application security. The source shelf connects each chapter to primary documentation so a new question has somewhere to go.

Sources: Rails guides, RFC 9110, RFC 9293