Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Chapter 18: Load Balancing

Chapter 17 introduced capacity decisions. Here we follow a visitor through the entry point, routing rules and selected target, then verify the application result. Health checks and their failure-handling exceptions are explained step by step.

In this chapter

  • One service name and multiple application targets
  • A request through the load balancer, step by step
  • Target capacity and the separate managed load-balancer resource
  • Manual balancing with two IP addresses, and what breaks when one server dies
  • Which balancer to choose: manual DNS, Application, Network, Gateway, or Classic
  • A target group: health checks, registering EC2, one listener, and a path rule
  • Round robin, least outstanding requests, and host or path rules
  • Application Load Balancer: example.com and api.example.com
  • Network Load Balancer: TCP port 443 passed through
  • Gateway Load Balancer, in brief, for a firewall appliance
  • Classic Load Balancer context and migration considerations
  • One app in two regions: each region has its own balancer
  • Target-group integration with an Auto Scaling group
  • Several target groups on one balancer, and more than one HTTP listener
  • A health check with numbers you set, and a /health path that returns 200
  • Internet-facing and internal balancers, and where each one sits in three tiers
  • Cross-zone load balancing on and off, and one domain name in front of two regions

This chapter uses the two EC2 instances and the target group idea from Chapter 17, Nginx or Apache from Chapters 6 and 8, and DNS from Chapter 9. The overview uses fictional names and temporary local exercises. Before any separate cloud lab, identify the authorised account, Region, owned resources, charges and cleanup plan.

People already know the feeling of one front door and many workers, even if they have never opened this console.

Fictional observation The honest lesson Result to verify
A college adds a second registration serverOne entry point routes requests to configured targets.The requested operation reaches the intended application.
A new release starts alongside the old releaseTraffic selection and release correctness are separate decisions.The selected release saves the expected registration.
A timetable probe succeeds while registration failsA probe establishes only its configured observation.The failed operation is traced to its actual stage.
A target is scheduled for removalNew assignment and existing work need a controlled retirement process.The remaining service meets its acceptance conditions.

The names represent teaching services. Distinguish name resolution, rule selection, target eligibility and the useful application result.

  User types example.com
        |
        v
  Name lookup obtains destination address information
        |
        v
  Load balancer (not an EC2 you installed Nginx on)
        |
        +--> EC2 A   healthy   "This is server A"
        |
        +--> EC2 B   healthy   "This is server B"

  This drawing shows two healthy example targets.
  Inspect actual target states and documented fail-open behavior.

Concepts in this chapter

  1. 18.1How a load balancer actually works
  2. 18.2How many EC2 instances
  3. 18.3Manual load balancing
  4. 18.4Which load balancer to use
  5. 18.5Target groups
  6. 18.6Routing policy
  7. 18.7Application Load Balancer
  8. 18.8Network Load Balancer
  9. 18.9Gateway Load Balancer
  10. 18.10Classic Load Balancer
  11. 18.11One app, multiple regions
  12. 18.12How this connects to scaling
  13. 18.13Multiple target groups
  14. 18.14Different HTTP listeners
  15. 18.15Health checks
  16. 18.16Internet-facing and internal load balancers
  17. 18.17Load balancer in a three-tier architecture
  18. 18.18Cross-zone load balancing, enabled and disabled
  19. 18.19One domain name, many regions, many load balancers

Review and practice

  1. ★Common Mistakes I See Students Make
  2. ★Interview Questions
  3. ★Practice Questions and Lab Exercises

Follow a request through routing and verification

Follow a request through routing and verificationName and connectionReach the intended entry pointRule and groupChoose the application serviceTarget operationReadiness is a limited observationResponse and recordVerify the useful result
Read all steps
  1. Name and connection

    The client resolves the hostname when needed and connects to the configured listener. For HTTPS it validates the server certificate. DNS does not choose an application by its later URL path.

  2. Rule and group

    The listener evaluates rules in priority order. A forwarding action selects the intended group, and target selection uses the applicable eligibility and routing configuration.

  3. Target operation

    The selected application handles the operation. A successful health probe does not prove that a registration was saved. Documented fail-open behavior also means an unhealthy label is not an access barrier.

  4. Response and record

    Compare the expected application response with the authoritative saved result. The local marker exercise demonstrates request routing and failure distinctions, not a real database transaction.

1. Give students one dependable entry point

Your college registration application now runs on two computers. Each computer has the same application release and can accept a workshop registration. There is still an unanswered question: when Mira opens the college website, which computer should receive her request? Giving her two addresses and asking her to choose would move an operating problem onto the student. She cannot know which server is busy, which one is being updated, or which one has stopped responding.

A load balancer provides an entry point and distributes incoming traffic to configured destinations called targets. For our registration example, those targets are application servers. The public website name remains useful while the set of servers behind it changes. The student follows the same link whether there are two eligible servers or four. This separation is valuable because the public identity of a service usually changes less often than the computers doing its work.

Think about the application operation before the machine count. A registration includes receiving the student's choice, checking eligibility, reserving a seat, storing the result and returning confirmation. Sending the request to a server is only one part. If both servers depend on a database that cannot accept another transaction, distributing more requests does not create more seats or database capacity. The load balancer helps connect work to available application capacity; the whole application still needs a sound design.

In AWS, Elastic Load Balancing is the service family. An Application Load Balancer, abbreviated ALB, is a useful starting point for our HTTP and HTTPS website. AWS operates the load-balancer infrastructure. You configure its network placement, listeners, traffic rules, targets and related controls. It is a different resource from an EC2 instance on which you personally install Nginx. Both can participate in proxying traffic, but their operating responsibilities and available features differ.

By the end of this overview, you should be able to draw a request path, explain each decision in it and interpret a failed result without guessing. The activities use fictional data and temporary local programs. They do not create an AWS load balancer, alter a domain, modify a security group or generate charges in an AWS account.

2. Follow one registration from name lookup to confirmation

Mira opens https://college.example/register. The hostname is college.example; the path is /register. These are different pieces of the address. DNS helps obtain destination address information for the hostname. It does not inspect the registration form or choose a server according to the URL path. A usable cached DNS result may avoid a new lookup for this visit.

For a domain using Route 53, an alias record can point at the selected load balancer, including at the domain apex. A CNAME is another DNS mechanism commonly used for an appropriate subdomain. The exact record must match the DNS provider and destination. The browser ultimately needs an address to connect to; it does not send HTTP traffic into a DNS hosted zone. Avoid copying one currently resolved ALB address into a permanent record as though that observation were its durable service identity.

The browser connects to the entry point using the chosen protocol and port. With HTTPS, it negotiates TLS and checks the presented server certificate for the requested name and trust requirements. A successful certificate check establishes something about this connection. It does not prove that the application has stored Mira's registration. That comes later in the operation.

The HTTPS listener accepts the connection. When the ALB handles the HTTP request, its rules determine the action for the requested host and path. In our design, requests for registration operations go to the registration target group. A routing algorithm and eligibility information then determine a target within the selected group. Suppose the selected destination is application server B on its configured application port.

The ALB-to-target connection is a separate part of the path. The server receives the request, validates the student's submitted values and performs the required database transaction. It then returns an HTTP response through the ALB to the browser. A useful success check compares the returned registration identifier with an appropriate read of the saved record. Merely seeing the website banner is insufficient evidence for this complete operation.

Keep a small observation sheet: requested hostname, URL path, response status, response marker, operation identifier and time. The marker can identify the application release in a controlled exercise. The identifier connects the user-visible confirmation to the stored result. Together they let you investigate a specific request instead of saying vaguely that the server works.

3. Separate the listener, rule, group and target

These four terms describe different decisions. A listener defines the protocol and port at which the load balancer accepts client connections. A rule evaluates relevant request information and selects an action. A target group holds routing and health settings for registered destinations. A target is an individual destination, such as a registered instance and its application port. Naming every component clearly makes the path easier to inspect.

Our fictional componentQuestion it answersExample observation
HTTPS listenerWhere does the browser connect?Client-facing HTTPS on port 443
Registration ruleWhich action matches this request?The registration path selects its group
Registration target groupWhich destination settings and membership apply?HTTP to the registered application port
Application BWhich destination handled the operation?The response contains the expected release marker

Do not assume the client port and target port must be equal. HTTPS may arrive on 443 while the application listens on a different configured port behind the entry point. The protocol choice for the second connection also matters. A correct browser-facing listener cannot compensate for selecting the wrong backend port or using HTTP against a backend that expects TLS.

For ALB, target types include instances, IP addresses and Lambda functions, with different constraints. This chapter's running example uses ordinary application-server targets. A target group is therefore more than a universal list of EC2 computers. Its type, protocol and supported configuration determine what may be registered and how traffic reaches it. An instance can also run more than one service; those services need separate identification through their intended ports and configuration.

Suppose the timetable and registration APIs run on the same two computers. You can still reason about separate timetable and registration target groups. The registration service might fail its specific probe while the timetable service continues responding. A statement that “the instance is running” hides this service-level distinction. Inspect the intended group and port before concluding that the target should receive a particular request.

4. Apply request rules before choosing a server

Our college serves the timetable and registrations through the same website. The timetable group handles /timetable; the registration group handles /register and its child paths. The rule chooses the service. Only after that choice does target selection decide which registration server receives the request. Confusing these stages leads to statements such as “round robin sends timetable requests to the registration application,” which describes a misplaced group configuration rather than the intended design.

ALB evaluates rules in priority order, with lower numbered priorities first and the default action last. A rule can forward, redirect or return a fixed response as its routing action. A redirect tells the client to make a request to another URL. Forwarding passes the request toward a target. A fixed response can answer without contacting an application target. Record which action occurred when interpreting a response.

Imagine a broad rule accepting every path for the college host appears before the registration-specific rule. The broad rule wins first, so the intended registration rule is never reached. Read conditions and order together. A matching path rule is not automatically the highest-priority rule, and a test of the home page does not exercise every route. Include a nested registration path and an unknown hostname in your test plan.

Matching a path and rewriting a path are separate operations. Current ALB rules support configured transforms, including URL and host-header rewrites. A path condition alone is not an instruction to remove a prefix. If the browser requests /api/register, the application must receive the path your design expects. Make an explicit choice and verify the application's observed path rather than assuming that a slash or prefix disappears.

The default action deserves a deliberate decision. In our exercise, an unrecognized host or path gets a clear fixed response instead of accidentally exposing a different application. This is a routing choice, not a substitute for application authorization. A registration handler must still check who may perform the operation, even if the request reached the expected group through an apparently correct rule.

5. Distinguish request distribution from completed work

Start with a small supplied example. Six requests arrive: four read a short timetable, one generates a large report and one submits a registration. If a simple alternating assignment sends three requests to each server, the number of requests is equal. The work may be very unequal. The report can take much longer than a timetable read. This explains why “each server received half” does not establish equal processor usage or equal completion time.

ALB offers round robin, least outstanding requests and weighted random target-selection algorithms. Round robin is the default. Least outstanding requests considers in-progress requests, while weighted random provides a different selection approach and supports Automatic Target Weights anomaly mitigation. Features such as stickiness, slow start and particular algorithm choices have compatibility restrictions. Select a supported combination and evaluate it against the workload instead of combining attractive feature names indiscriminately.

A small browser refresh sample is not a benchmark. Existing connections, cookies, target eligibility and the chosen algorithm affect what you observe. For a useful comparison, define the operation mix, observation interval, offered load and success criteria. Count completed useful operations and errors as well as arrivals. An application that rapidly rejects every registration could produce short response times while failing its purpose.

Now consider two separate release groups called blue and green. A forwarding rule can assign weights to those groups. This is a different choice from selecting an individual target within a group. A small sample need not reproduce the configured proportion exactly. More importantly, an empty or entirely unhealthy weighted group does not automatically transfer its assigned traffic to the other healthy group. Plan monitoring and reversal of the release separately.

For example, a trial release should be judged by whether its own registrations are correct, not only by an overall site average dominated by the old release. Keep separate observations for each release marker and operation. Before changing a weight, establish what result would cause you to stop the trial and whether the older code can still understand data written by the newer version.

6. Read health as the result of a particular check

A health check asks a configured question repeatedly. With an ALB HTTP target group, settings identify details such as protocol, port, request path, expected success codes, timing and thresholds. A target marked healthy has met the applicable probe conditions. It has not passed every conceivable business operation. A page that always returns “ready” can conceal a failed database connection if that page never tests the dependency.

Design the check around the traffic decision it supports. A process-alive check can help distinguish a stopped process from a running one. A readiness check can ask whether this particular target can currently accept the intended operation. A separate synthetic transaction can test a representative user journey. Combining every dependency into every frequent probe can also create unwanted behavior, such as withdrawing all application targets during a shared dependency problem. Explain the intended meaning before selecting the implementation.

Read the reason code when a target is unhealthy or unused. A response-code mismatch suggests a different next investigation from a timeout. The ALB health-check request's host information may differ from your public hostname, which matters for applications that select virtual hosts. A successful test using your laptop's browser does not automatically reproduce the request sent by the load balancer.

There is an important exception to the simple “healthy targets only” description. ALB can fail open: when the registered targets are all unhealthy across the enabled zones, requests can still be routed to them. Configured target-group health thresholds also influence failure handling. An unhealthy label must therefore not be used as a security barrier or as proof that the server will receive no traffic. Failing open does not repair the target or promise a successful response.

In our college case, suppose both servers return a successful timetable response but cannot save a registration. A shallow health check can remain successful while students fail to enrol. The next useful evidence is the specific registration request and database error, not another screenshot of a green target count. Conversely, an incorrectly configured probe can mark a working application unhealthy. Investigate both the check and the operation it is meant to represent.

7. Choose the load balancer from the traffic requirement

Start with a sentence describing the work. “We need different URL paths to reach different college applications” points toward application-aware HTTP routing. “We need a particular TCP service with a stable network entry arrangement” asks a different question. “We need to distribute inspected traffic through compatible firewall appliances” is different again. Choosing by requirement is easier to defend than choosing whichever acronym you learned most recently.

TypeMain teaching roleQuestion to investigate
Application Load BalancerHTTP and HTTPS application routingWhich host, path and application rules are required?
Network Load BalancerTransport-level traffic distributionWhich protocol, address behavior and connection properties are required?
Gateway Load BalancerTraffic distribution through virtual network appliancesWhich compatible inspection appliances and routed traffic path are required?
Classic Load BalancerAn older supported load-balancer typeWhat existing behavior must be preserved during any migration?

An NLB can pass encrypted TLS traffic through a TCP listener so that the target handles decryption. A TLS listener instead terminates TLS at the NLB. These are different designs even if the client connects to port 443 in both. Current NLB protocols also include QUIC and combined protocol options; supported combinations, IP address requirements and security-group restrictions depend on the chosen configuration. Do not memorize an old exhaustive protocol list as a permanent service limitation.

For an NLB, a flow or connection is an important unit of distribution. One long-lived connection does not become many independently balanced application messages simply because it carries a lot of data. If one client connection remains on one target, that observation is not sufficient to diagnose a broken balancer. Compare the protocol's behavior and connection pattern with your expectations.

Gateway Load Balancer serves a network-appliance use case. It forwards traffic through compatible appliances using GENEVE on port 6081. It is not a more advanced replacement for ALB host-and-path routing. A firewall inspection design needs correct routes, endpoint arrangements and return paths as well as appliance capacity. Recognize this role without trying to insert it into every small website architecture.

Classic Load Balancer remains relevant when reading existing environments. A migration creates a new arrangement whose listeners, checks, certificates and application behavior must be compared. It is not automatically an in-place conversion that preserves every detail. For a new registration design, compare the current ALB and NLB capabilities against your actual requirements; for an existing service, preserve working behavior and prepare a reversible transition.

8. Place capacity across zones and understand its scope

An Availability Zone is a placement boundary within an AWS Region. Two application instances in one zone are still exposed to a shared zone failure. Placing appropriate capacity across zones can reduce that dependency, but only if the remaining capacity and the other application components can support the service. Drawing two boxes does not prove that either box has a usable release or access to the required data.

For an ordinary regional ALB, use subnets in at least two Availability Zones and consider the placement of its targets. Special deployment environments have their own requirements. An internet-facing entry point can reach application targets through their private addresses. The application targets do not need public addresses merely because visitors use the public website. Your subnet routes and network controls still need to support the intended connections.

Cross-zone load balancing concerns which zones' targets a load-balancer node can use. It is a routing scope decision. ALB enables it at the load-balancer level, while supported target-group configuration can disable it for that group. NLB and GWLB have different defaults. Always read the effective setting for the actual resource rather than carrying an assumption from a different load-balancer type.

Use an invented planning worksheet: zone A has one target and zone B has three. Suppose, only for this arithmetic exercise, each zone's entry point receives forty requests. If each entry point uses only local targets and shares work evenly, A's target gets forty while each B target gets about thirteen. If every entry point can use all four targets, an idealized even distribution would give each twenty. These numbers describe the worksheet's assumptions, not a measured AWS distribution.

The more important question is what happens when one zone is unavailable. If only one target remains, can it meet the required operation rate? What happens to connections already in progress? Can the data layer continue its role? Cross-zone routing does not create replacement capacity or replicate the database. Work backward from the remaining usable service rather than treating a checkbox as a complete availability design.

9. Check each connection and each trust decision

Draw three separate arrows for the college application: browser to ALB, ALB to application, and application to database. Write the protocol, destination port and permitted source beside each arrow. A browser successfully reaching the first arrow is no evidence that the third is permitted. This simple drawing prevents the common habit of changing unrelated rules whenever a page fails.

The ALB security group must permit the intended client traffic and communication with targets. Target rules can reference the ALB's security group as the source for the intended application and health-check ports. Network ACLs, routes, the guest operating system and the actual listening process also matter. Opening a security-group port does not start the application, and configuring an application port does not create a route.

For HTTPS, the browser-facing certificate must cover the requested hostname. A wildcard such as *.college.example covers one subdomain level; it does not automatically cover the bare college.example name or a deeper name such as reports.staff.college.example. Certificate choice and routing choice are separate checks. A correct host rule cannot repair a certificate mismatch encountered during TLS negotiation.

Protecting the second connection with HTTPS is another decision. ALB can use TLS to targets, but it does not perform browser-style validation of those target certificates. Therefore, “both links use encryption” and “both peers are validated exactly as a browser validates a public site” are different claims. Explain the actual trust model and network boundaries in the design instead of merging them into one green-lock symbol.

An application behind a proxy may need the original client address and original request scheme. ALB supplies forwarded headers for these purposes. The application must trust only the appropriately controlled proxy path and interpret the header chain correctly. Accepting an arbitrary client-supplied address header as identity can produce incorrect logs or access decisions. A forwarded address also does not establish who the student is; application authentication and authorization still have their own work to do.

10. Keep student state correct when the target changes

Mira logs in through server A and then opens her saved registrations. If A stored the only copy of her session in its own memory, a subsequent request to B may not find it. Both servers can be running the correct code, and the load balancer can be distributing requests as configured, while the student sees an unreliable login. The missing piece is the application's handling of state.

Session affinity, often called stickiness, attempts to keep related traffic on the same selected target under the configured rules. It does not copy a session to another machine, back up an uploaded document or guarantee that A will remain available. If A is replaced, the design still needs a way to handle the student's next request. Shared session storage is one possible approach; validated self-contained tokens are another design choice with different security and lifecycle requirements.

Separate temporary session state from durable business records. A login session explains an authenticated interaction. A saved registration records the accepted workshop choice. Losing a session might require signing in again, whereas losing the registration would lose a business result. Give these data types their own storage and recovery decisions. Do not keep the only authoritative registration record in an individual server's temporary memory.

The same reasoning applies to uploaded files and background jobs. A file saved only on A may be missing when B handles a later download. A background task started by A may be interrupted when A is removed. The application needs appropriate shared storage, durable task ownership or other explicit mechanisms. The load balancer does not automatically merge local directories or transfer an executing job between processes.

Retries need special attention. If the registration commits but the response is lost, repeating the operation can create a duplicate unless the application handles repeated intent safely. A stable operation identifier and database constraints can help, but their exact implementation must cover concurrency and failure cases. Routing the retry to the same target is not a complete substitute for a correct operation design.

11. Coordinate target membership, startup and removal

Load balancing distributes traffic; EC2 Auto Scaling manages intended instance capacity. When the appropriate target group is attached to an Auto Scaling group, its lifecycle integration registers launched instances and deregisters departing ones. The group can also use configured load-balancer health checks for replacement decisions. These integrations require the intended settings; adding an ALB does not automatically configure every scaling policy or health source.

Consider a new server C. It must obtain the intended release, configuration and dependencies before it can reliably handle a student's registration. Its instance can exist before its application is ready. The target's readiness, the scaling system's warmup treatment and the health-check grace period answer different questions. A grace period is not an instruction to stop every health probe or to send traffic to unfinished code.

Removing A requires planning for requests already using it. Deregistration stops new assignment as the target drains, with the configured delay allowing time for existing work. This does not promise unlimited time for every operation or automatically complete unrelated background jobs. Match application shutdown and connection handling to the retirement process. An abrupt process stop can interrupt a request even if the infrastructure change itself reports success.

A useful release rehearsal follows four observations: old release works; candidate becomes ready; representative operations reach the candidate successfully; removal of the old target does not violate the chosen acceptance conditions. Record both the deployment marker and the saved registration. Repeating only a health endpoint can miss a broken business path introduced by the new release.

Finally, scale the part that limits useful work. If every application server is waiting on the same slow database query, adding more can increase the queue at that dependency. Compare completed registrations, errors and latency after a capacity change. The target count is an operating input; students experience the result of the complete system.

12. Investigate a failure using evidence from the right stage

Begin with the student's exact observation. “Registration failed at 10:15” is more useful when it includes the requested name and path, response status and operation identifier. Ask whether the browser reached the intended entry point and whether the request was forwarded to an application target. This separates a connection failure from a routing mistake and an application error.

ALB access logs can record the request, selected target information, timing and response fields. Logging must be configured; do not assume historical records exist merely because the load balancer exists. Current logging options include enhanced delivery choices as well as the traditional S3 access-log arrangement. Access logs are delivered on a best-effort basis, so use them as diagnostic evidence rather than an infallible accounting ledger for every registration.

Distinguish an error generated by the load balancer from an error returned by its target. Correlate the load-balancer status and target status fields with the application log. A 500 returned by the registration handler asks a different question from a request that never reached a target. A 404 can be a deliberately configured fixed response, a wrong application route or a missing resource. The number alone does not identify the responsible component.

CloudWatch metrics help summarize changes over time. Useful examples include healthy target counts, target response time and the separate load-balancer and target error metrics. Select the correct resource dimensions, statistic and time interval. An average across the whole application can conceal a failing registration group or one troubled zone. A graph with missing observations is not automatically a graph of successful zero-error operation.

Write the next check as a discriminating question. If the target's private endpoint responds correctly to the configured probe but the ALB reports a timeout, compare the actual source path and permissions. If the ALB selects the timetable group for a registration request, inspect rule order. If the registration reaches the right release but the database rejects it, follow the application transaction. Each observation should narrow the next investigation.

13. Keep regional routing separate from regional recovery

A regional load-balancer design and a multi-Region design solve different placement problems. You can deploy a registration service in two Regions and use a higher-level entry or DNS arrangement to choose between them. Route 53 routing policies influence DNS answers; examples include latency-based and failover policies. They do not inspect each later HTTP path inside a browser connection.

Changing the selected Region does not move the student's records. The secondary application needs compatible code, configuration, certificates, capacity and access to data with an understood freshness level. If yesterday's registrations are present but this morning's are absent, successfully opening the secondary home page is not proof of complete recovery. Define which operations can continue and how uncertain or conflicting writes are handled.

DNS caching and existing connections also matter during a transition. A control-plane change does not make every client instantly forget its earlier answer. Rehearse the application's observable behavior, including old and new destinations, instead of promising a universal cutover time. The detailed regional lessons build on this distinction between selecting a destination and proving that the selected destination can deliver the promised service.

14. Practice routing and failure handling on your own computer

Lab A: predict the route before running the model

This first exercise needs Python 3 and makes no network requests. Copy the complete block into a local Python session or a temporary script. Before running it, write the expected result for each host and path. Pay particular attention to /registering: a similar word is not automatically the same route as /register. Our function deliberately defines exact and child-path behavior.

The function represents the decisions in a small fictional rule sheet. It is not an ALB configuration parser and does not implement AWS wildcard or regular-expression matching. The purpose is to distinguish matching conditions from evaluation order. Five assertions compare the output with independently listed expectations. A sixth check adds an earlier broad rule and demonstrates that the intended registration rule becomes unreachable for that request.

def choose(host, path, broad_first=False):
    if broad_first and host == 'college.example':
        return 'timetable'
    if host == 'college.example' and (path == '/register' or path.startswith('/register/')):
        return 'registration'
    if host == 'college.example' and path == '/timetable':
        return 'timetable'
    return 'fixed 404'

cases = [
    ('college.example', '/register', 'registration'),
    ('college.example', '/register/status', 'registration'),
    ('college.example', '/timetable', 'timetable'),
    ('college.example', '/registering', 'fixed 404'),
    ('unknown.example', '/register', 'fixed 404'),
]
for host, path, expected in cases:
    actual = choose(host, path)
    assert actual == expected
    print(host, path, '->', actual)

assert choose('college.example', '/register', broad_first=True) == 'timetable'
print('An earlier broad rule hides the intended registration rule')

Explain the results in words. The registration root and its status child select registration. The timetable selects timetable. The similar but different path and unknown hostname receive the explicit fallback. When the broad rule comes first, it captures the request before the specific rule can decide. To extend the worksheet, add one new legitimate route and one nearby invalid route, and write both expected answers before editing the function.

Lab B: observe two real local servers through a small front process

The next exercise uses Python 3.9 or later and only the standard library. It starts three temporary HTTP listeners on 127.0.0.1 with operating-system-assigned ports: backend A, backend B and a front process. It sends requests to these loopback listeners, then closes them. It writes no registration database, changes no system configuration and contacts no AWS resource. Run the entire block together in a local Python script or session.

The backend endpoint named /register returns a marker; it does not save a student. This keeps the observable routing behavior separate from a real business transaction. The front process checks each backend's readiness immediately before each test request, then alternates among eligible destinations. AWS uses its own distributed health-check and routing mechanisms. In particular, our local front deliberately returns 503 when no backend is ready; it does not reproduce ALB fail-open behavior.

Predict five phases: both ready; B not ready; A's probe succeeds while its operation fails; neither ready; recovery. The program checks each prediction. Keep the printed results so you can compare the phase with its expected status and marker. If an assertion fails, inspect that specific phase before changing the expected answer. Do not remove assertions simply to obtain a successful final line.

from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from urllib.request import build_opener, ProxyHandler
from urllib.error import HTTPError

client = build_opener(ProxyHandler({}))
state = {
    'A': {'ready': True, 'operation_ok': True},
    'B': {'ready': True, 'operation_ok': True},
}
servers, threads, targets = [], [], []
turn = 0

def read(url):
    try:
        with client.open(url, timeout=3) as response:
            return response.status, response.read().decode()
    except HTTPError as response:
        with response:
            return response.code, response.read().decode()

class QuietHandler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def reply(self, status, body):
        data = body.encode()
        self.send_response(status)
        self.send_header('Content-Type', 'text/plain; charset=utf-8')
        self.send_header('Content-Length', str(len(data)))
        self.end_headers()
        self.wfile.write(data)

def backend(name):
    class Backend(QuietHandler):
        def do_GET(self):
            if self.path == '/ready':
                self.reply(200 if state[name]['ready'] else 503, name)
            elif self.path == '/register':
                status = 200 if state[name]['operation_ok'] else 500
                self.reply(status, 'served=' + name)
            else:
                self.reply(404, 'unknown backend path')
    return Backend

class Front(QuietHandler):
    def do_GET(self):
        global turn
        if self.path != '/register':
            self.reply(404, 'unknown front path')
            return
        eligible = [url for url in targets if read(url + '/ready')[0] == 200]
        if not eligible:
            self.reply(503, 'no ready targets in this local exercise')
            return
        destination = eligible[turn % len(eligible)]
        turn += 1
        status, body = read(destination + self.path)
        self.reply(status, body)

def start(handler):
    server = HTTPServer(('127.0.0.1', 0), handler)
    servers.append(server)
    worker = Thread(target=server.serve_forever, daemon=True)
    worker.start()
    threads.append(worker)
    return 'http://127.0.0.1:' + str(server.server_port)

try:
    targets.extend([start(backend('A')), start(backend('B'))])
    front = start(Front)
    first = [read(front + '/register') for _ in range(4)]
    assert first == [(200, 'served=A'), (200, 'served=B')] * 2
    print('Both ready:', first)

    state['B']['ready'] = False
    second = [read(front + '/register') for _ in range(3)]
    assert second == [(200, 'served=A')] * 3
    print('B not ready:', second)

    state['A']['operation_ok'] = False
    assert read(targets[0] + '/ready')[0] == 200
    assert read(front + '/register') == (500, 'served=A')
    print('A probe: 200; A operation: 500')

    state['A']['ready'] = False
    assert read(front + '/register')[0] == 503
    print('No ready targets: local front returns 503')

    for record in state.values():
        record.update(ready=True, operation_ok=True)
    assert read(front + '/register')[0] == 200
    assert read(front + '/unknown')[0] == 404
    print('Recovery: 200; unknown path: 404')
finally:
    for server in reversed(servers):
        server.shutdown()
        server.server_close()
    for worker in threads:
        worker.join(timeout=3)
    assert all(server.fileno() == -1 for server in servers)
    assert all(not worker.is_alive() for worker in threads)
    print('All local listeners closed')

In the first phase, four sequential requests return A, B, A and B. This is a deterministic result of our tiny front process. It is not evidence that four refreshes through an AWS load balancer must follow the same sequence. In the second phase, B's readiness response changes, and all three subsequent requests use A. The destination list changed because the supplied readiness observation changed.

The third phase is the key learning point: A still returns 200 for its readiness path but returns 500 for the operation path. Our probe is too narrow to establish operation success. In the fourth phase, the front returns its own 503 because its local eligibility list is empty. Compare that explicit implementation with the ALB behavior explained earlier. A useful model states both the mechanism it demonstrates and the service behavior it does not reproduce.

Recovery restores both state records, checks a successful operation response and verifies a separate unknown-path 404. The finally block shuts down and closes the listeners even if a later assertion fails. Its final assertions confirm closed server sockets and stopped serving threads. This cleanup belongs to the exercise: a complete lab includes the state left behind after the observations, not just the moment of success.

To explain the code, find four places: the backend's response decision, the front's eligibility list, the destination selection and the cleanup block. You do not need to memorize every Python line. You need to connect those parts to what you observed. This program is a deliberately limited teaching fixture, not a production proxy; Python's simple HTTP server also is not recommended as a production web server.

15. Explain the reasoning in an interview

1. Walk through a registration request behind an ALB.

Begin with the hostname and DNS result, then the client connection and HTTPS certificate check. Explain that a listener rule selects an action and target group, after which the group selects an eligible target. The application processes the operation and returns a response through the ALB. Finish by checking the saved registration, because a delivered page does not prove that a transaction committed.

2. Can a single target be used behind a load balancer?

A target group can route to one registered target in an appropriate configuration. That does not create redundant application capacity. If the only usable target fails, the service still has an application-level dependency on it. Distinguish the number of targets from the load balancer's subnet and zone requirements. Explain the consequence of the chosen placement instead of quoting a universal “minimum two servers” rule.

3. A target is healthy but students cannot register. Where do you investigate?

Read what the probe actually checks, then follow a failing registration request. Compare the selected group, application release, operation response and database evidence. A shallow probe may succeed while the database operation fails. The local lab demonstrates precisely this distinction with a 200 readiness response and a 500 operation response from the same backend.

4. Does an unhealthy ALB target always stop receiving traffic?

No. Ordinary healthy-target selection has documented failure-handling exceptions, including fail-open when the registered targets are all unhealthy across enabled zones. Inspect the actual health thresholds and target states. Never use an unhealthy label as an access-control mechanism. Explain that routing a request during fail-open still does not make the target capable of completing it.

5. Explain the difference between a host rule and round robin.

A host rule selects an action based on request information, potentially choosing a target group. Round robin is a way to select targets within the applicable group. The decisions occur at different stages. In our college example, a registration rule chooses the registration service; a target-selection algorithm then chooses one registration server. Fixing an incorrect rule order requires inspecting rules, not changing the target algorithm at random.

6. Will sticky sessions protect a student's uploaded file?

Stickiness can influence which target receives later requests, but it does not replicate the file. If its only copy is on a departing server, traffic affinity cannot recover it. Identify the file's authoritative storage, access path and recovery requirements. Treat session affinity as a routing feature and data durability as a storage-and-application design responsibility.

7. A green release has no ready targets. Will its weight move automatically to blue?

An ALB weighted forwarding arrangement does not automatically fail over an empty or all-unhealthy weighted group to another healthy group. You need a deliberate release response and verification plan. Compare release-specific errors and useful outcomes, then apply the approved traffic change or rollback. Also consider whether records written by the new release remain compatible with the old application.

8. Explain balancing and scaling without using their names as the definition.

One mechanism decides where arriving work goes among configured destinations. The other changes the intended amount of instance capacity and manages its lifecycle. They cooperate through target registration and health-related configuration. Neither alone guarantees that a student can complete an operation: the new server must become ready, the remaining servers must have capacity, and shared dependencies must still work.

16. Check your understanding before opening the answers

Answer each question with a conclusion and the observation that supports it. A correct guess is less useful than a correct explanation you can repeat in a lab.

1. DNS resolves correctly, but /register reaches the timetable application. What should you inspect?

Inspect listener conditions, priority order and the resulting action. DNS resolution identifies destination information for the hostname; it does not select a target group based on the later HTTP path. Confirm the actual group and application marker before changing records.

2. Two servers receive equal request counts. Must their CPU usage be equal?

No. Requests can require different amounts of work, and the servers may differ in capability or current state. Compare operation mix, processing time, errors and completion rate. Equal assignment counts are one observation, not a complete capacity measurement.

3. In the local lab, why does the front return 503 when neither target is ready?

The teaching program explicitly implements that action for an empty eligibility list. It is a property of the local code. Do not generalize it to ALB, whose documented fail-open behavior can still route to unhealthy registered targets.

4. Does moving traffic to another Region move the database records?

No. Destination selection and data availability are separate responsibilities. Check replication or recovery design, freshness, compatible application configuration and the handling of new writes before declaring the secondary service ready.

5. Is a successful readiness check enough to accept a new release?

No. It establishes the result of that configured probe. Test a representative application operation, confirm the expected release and inspect its useful result. Include failure and recovery observations appropriate to the change.

17. Use these revision cards to rebuild the request path

Listener

The client-facing protocol and port entry. Identify it separately from the target's application port and from network permission to reach either endpoint.

Rule

A condition-and-action decision in an ordered set. Verify both the matching request and the earlier rules that could capture it.

Target group

The applicable target membership, routing and health configuration. A healthy result in one group does not prove a different service or port works.

Health check

A repeated observation with defined conditions. Explain the question it asks, the result it establishes and the operations it does not test.

State

Session information, files and durable business records need explicit ownership and storage. Sending two requests to the same server does not provide a backup.

Recovery

Verify the restored service with expected content and a useful operation. A recovered target count or changed DNS answer is only part of that evidence.

18. Complete the chapter with an evidence-based operating note

  1. Draw the path. Label the hostname, client-facing listener, registration rule, target group, target port and database connection. Explain the evidence you would collect at each stage.
  2. Write a routing matrix. Include the intended registration path, a nested path, the timetable, an unknown host and a similar but invalid path. Predict every result before running Lab A.
  3. Record the local experiment. For each Lab B phase, write the readiness condition, response status, destination marker and meaning. Include the final listener-cleanup result.
  4. Describe a controlled release. State the baseline, candidate readiness checks, representative operation, stopping condition and return path. Explain how you would avoid confusing a healthy probe with a valid registration.
  5. Plan a separately authorised cloud lab. Identify the account, Region, owned resources, expected charges and cleanup responsibilities before creating anything. Preserve observations first, remove only lab-owned dependencies in the appropriate order, and verify that unrelated services still work.

Your operating note should allow another student to repeat your reasoning without guessing what “working” meant. Include the result that would disprove your conclusion. For example, a successful timetable plus a failed registration disproves a claim that the entire application is healthy. This habit turns familiar service names into a practical troubleshooting method.

Official references and further reading

Service-specific details were checked against the primary references below. The fictional college scenarios, arithmetic assumptions and local teaching programs are original exercises.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. The tasks below are browser-only answer exercises for this fictional scenario. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy List hosted zones

You need the zone ID to change records.

List all hosted zones in the account.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Check target health

Compare target health, request status and logs; an unhealthy target alone does not identify one universal HTTP response.

Show the health of the targets in arn:aws:elasticloadbalancing:ap-south-1:120348739971:targetgroup/amravatiagro-tg/6d0ecf831eec9f09.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Register servers in the target group

Register the intended targets and inspect their health, eligibility and documented failure-handling behavior.

Register instance i-01bdd3bc430211a2b in target group arn:aws:elasticloadbalancing:ap-south-1:120348739971:targetgroup/amravatiagro-tg/6d0ecf831eec9f09.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Create a target group

A target group defines registered destinations and their routing and health-check settings.

Create target group amravatiagro-tg for HTTP on port 80 in vpc-034fa3eea1deadbee.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Kubernetes LoadBalancer Service

A Service of type LoadBalancer relies on the installed cloud integration or controller and its configuration.

Write a Service of type LoadBalancer selecting app: web, port 80 to targetPort 8080.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium Create a hosted zone

A hosted zone holds records for its DNS namespace; delegation and public or private scope determine which queries use it.

Create a public hosted zone for amravatiagro.in, with caller reference amravatiagro-2026-01.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create an Application Load Balancer

For this ordinary regional ALB exercise, select subnets in at least two Availability Zones and verify target placement and health.

Create an ALB named amravatiagro-alb in subnets subnet-02034cb3ddb1bb1 and subnet-0034cb3ddb1bb2 with security group sg-02034ba3cca14c3b2.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Add an HTTP listener

The listener accepts the configured protocol and port; its rules determine the applicable action, including forwarding in this exercise.

On load balancer arn:aws:elasticloadbalancing:ap-south-1:120348739971:loadbalancer/app/amravatiagro-alb/50dc6c495c0c9188, create an HTTP listener on port 80 that forwards to arn:aws:elasticloadbalancing:ap-south-1:120348739971:targetgroup/amravatiagro-tg/6d0ecf831eec9f09.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create a Network Load Balancer

An NLB distributes supported transport traffic; verify its current protocol, address and security configuration requirements.

Create a network load balancer named amravatiagro-nlb in subnets subnet-02034cb3ddb1bb1 and subnet-0034cb3ddb1bb2.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Create or update a DNS record

UPSERT creates the record or updates it if it already exists.

Apply the record changes in change.json to hosted zone Z0123456789ABCDEFGHIJ.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.