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

AWS Cloud

Chapter 17: Scaling

Let's go. In Chapter 14 we made one server bigger: stop, change the instance type, start. Today we look at the whole picture of scaling. Making one server bigger, adding more servers, a CloudWatch alarm, an SNS email, and an Auto Scaling group whose intended capacity changes through configured policies, schedules or manual actions. Don't worry, you will get it.

In this chapter

  • Why one server runs out of CPU or memory, and when a bigger type is the wrong fix
  • Vertical scaling on the fictional site: compare the actual resource and credit characteristics before changing an instance type
  • Horizontal scaling: two t3.micro instances behind one load balancer
  • Manual scaling: a second instance from the same AMI, and desired capacity by hand
  • A CloudWatch alarm with the numbers written out: CPU greater than 70 for 2 periods of 5 minutes
  • SNS: create a topic, confirm the email, notify on ALARM and on OK
  • An Auto Scaling group with minimum 1, desired 1, maximum 3: the alarm moves desired from 1 to 2, then scale-in brings it back to 1
  • A sudden rush in shopping, payments, video, food, tickets, exams, and a viral reel, and what the alarm does while you sleep
  • When the limit is CPU, RAM, or the disk
  • How Nginx and Apache use workers, and how change ordering affects availability
  • Manual, simple, step, target tracking, scheduled, and predictive scaling
  • How to put the lab back when class ends, with no prices
  • Public incidents where a real site slowed under demand

This chapter uses the EC2 instance from Chapter 5, the type change from section 14.4, and the AMI from section 14.2. The site in every example is example.com. The expanded overview uses offline models. For a separate authorised cloud lab, review the account, Region, resource ownership, charges and cleanup plan before making changes. When the lab is finished, do not leave extra instances running.

People already know what a traffic spike feels like, even if they have never opened the AWS console.

What you have seen The honest lesson What this chapter will not invent
A fictional registration opening receives many submissionsMeasure arrivals, completions, latency and errors before choosing a capacity change.No claim about a named company or its infrastructure.
A fictional application spends time on independent calculationsAdditional compatible workers may help if requests and dependencies support the concurrency.No promise that doubling workers halves resource usage.
A fictional database working set needs more memoryA suitable resource change may help after evidence identifies that constraint.No guarantee that every larger instance has more processors.
A fictional report queue keeps growingCompare arrival rate with completion rate and inspect the shared bottleneck.No assumption that an unlimited queue creates unlimited capacity.

example.com in this lab is a small teaching site, not those apps. The teaching question is which part of the path limits useful work. Resource changes, workload improvements and admission controls can address different parts of that problem. The public site name can remain the same while its serving arrangement changes.

  Visitors type example.com
            |
            v
  Load balancer (one DNS name)
            |
            +--> application target   verify readiness and actual load
            |
            +--> application target   verify readiness and actual load

  The earlier 90% CPU value is a supplied observation, not a scaling guarantee.

  Chain when CPU stays high:
  the selected CPU statistic exceeds 70 for the configured 2-of-2 evaluation
        --> alarm state ALARM
              --> SNS email (only if the subscription is Confirmed)
              --> scaling policy sets desired 1 --> 2
                    --> group attempts the launch; readiness and useful operation still need checks
  Later, when CPU stays low:
        --> scale-in sets desired 2 --> 1
  Minimum is 1, so the group does not go to zero.
  Configured desired maximum is 3 in this equal-instance example.
  Documented replacement/rebalancing behaviour is not a hard bill cap.

Concepts in this chapter

  1. 17.1Vertical scaling (scale up)
  2. 17.2Horizontal scaling (scale out)
  3. 17.3Manual scaling
  4. 17.4CloudWatch alarm
  5. 17.5SNS: email when the alarm changes
  6. 17.6Auto Scaling
  7. 17.7What happens when traffic increases
  8. 17.8CPU, RAM, or storage
  9. 17.9How Nginx and Apache use CPU and RAM
  10. 17.10No downtime: the order
  11. 17.11Every Auto Scaling policy
  12. 17.12When class ends
  13. 17.13Public reports, not our clients

Review and practice

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

Follow demand into useful serving capacity

Follow demand into useful serving capacityObserved demandMeasure the operation and bottleneckCapacity decisionDesired is an intended statePrepared instancesInitialize and verify readinessVerified serviceMeasure improvement and retire safely
Read all steps
  1. Observed demand

    Record incoming work, completed operations, latency and errors. The model uses a supplied application capacity and a shared database limit; these are assumptions rather than benchmark claims.

  2. Capacity decision

    A configured policy, schedule or manual action changes the target capacity. An accepted decision does not establish that additional instances have launched successfully or can serve students.

  3. Prepared instances

    Check the release, configuration, dependencies and traffic eligibility. Startup and metric stabilisation take time. Count useful serving capacity separately from desired and merely launched capacity.

  4. Verified service

    Compare representative operations under the intended demand. When removing capacity, stop new assignment appropriately and handle existing work through the designed retirement process.

1. Start with the student's experience of a busy website

Your college opens workshop registration at nine in the morning. Before nine, a few students read the timetable. At nine, many students submit reservations together. A timetable request might only read a small file, while a reservation validates a student, checks capacity and writes a database record. Counting both as one request does not mean that both require the same amount of work.

Scaling means changing the resources available to handle a workload. We care about the result: students should complete valid operations within an acceptable time, with the correct records saved. A dashboard showing more servers is not enough. If those servers are still starting, cannot reach the database or all share the same overloaded dependency, useful capacity may barely have increased.

Demand describes work arriving. Throughput describes work completed over a period. Latency describes how long an operation takes from the chosen starting point to its result. Errors describe unsuccessful outcomes, but their meaning needs care: a deliberate rejection because a workshop is full differs from a database timeout. Track both technical responses and the intended business outcome.

Suppose one application server completes forty representative reservations per second while meeting the class's fictional latency target. That is a measured result for one workload and environment, not a permanent property of its instance type. Changing the query, database contents, application release or request mix can change the result. A capacity estimate should state these conditions so another student knows what it means.

If sixty reservations arrive each second but only forty finish, unfinished work accumulates unless the system rejects or redirects some requests. That growing queue increases waiting time. Giving a request a longer timeout may let it wait longer, but does not create processing capacity. The team must examine the bottleneck and decide whether to add capacity, reduce work, control admission or combine those approaches.

Our examples use fictional numbers and offline programs. They help you reason about capacity and timing without generating traffic against a real website. Before any real load test, use an authorised environment, an agreed workload and clear stop conditions. This chapter's objective is to make each scaling decision explainable, rather than to produce a dramatic CPU graph.

2. Find the resource that limits useful work

A bottleneck is the part of the path that limits progress for the workload being observed. It can move after a change. The application may initially spend most of its time calculating a result. After adding application capacity, the shared database may become the limiting part. Improving one stage does not make the rest of the path unlimited.

CPU pressure means that processing demand is competing for the available processor time. Memory pressure concerns the working data that processes need to keep available. Storage can be limited by capacity, throughput, operation rate or latency. A network path can be constrained by bandwidth, connection handling or another resource. These categories are starting points for investigation, not diagnoses based on a single percentage.

High CPU can be useful work or an avoidable problem. A sudden loop in application code may consume every new server you add. Low CPU does not prove spare useful capacity either: workers can spend time waiting for a database lock or external service. Compare resource metrics with request timing, application logs and dependency observations before choosing a scaling action.

Averages can hide uneven load. If one server has a hot session or an unusually expensive request while others are quiet, the group average may appear comfortable. Look at the distribution across instances and relevant tail latency. The ninety-fifth percentile is a threshold at or below which ninety-five percent of the observed durations fall; it tells a different story from the arithmetic mean.

Also separate real overload from a changed workload. Sixty small timetable reads and sixty expensive reports have the same request count but different costs. A useful comparison holds the workload shape reasonably constant or explicitly explains the change. Record request type, data size and concurrency along with the result.

For the workshop, make a short evidence table: the affected operation, its observed duration, where it waits, resource observations and the proposed change. If most time is waiting on the same database query, adding web servers deserves scepticism until you understand that query. If independent application calculations dominate and the work distributes well, more application capacity is a more plausible experiment.

3. Compare a stronger server with additional servers

Vertical scaling changes the capabilities assigned to a component, such as selecting an EC2 instance type with more suitable memory or compute resources. Horizontal scaling adds more components that can share suitable work. Scaling down and scaling in reverse these directions. The words describe resource changes, not a guarantee about how much faster the application becomes.

A compatible in-place EC2 type change for an EBS-backed instance requires stopping it, changing the type and starting it. That interrupts the application on that instance and has storage and address consequences discussed in the EC2 operations chapter. A replacement-based approach has different steps. Check compatibility and operating ownership before treating a type change as a quick fix.

The size label alone is insufficient. Two neighbouring sizes can have the same vCPU count but different memory and burst characteristics. For example, the T3 micro and small sizes both have two vCPUs; their baseline CPU and credit arrangements differ. Moving between them does not mean that a CPU-heavy operation receives twice the number of processors.

Burstable instances use CPU credits to support work above their baseline. Standard and Unlimited modes handle sustained demand differently, including possible additional charges in Unlimited mode. A short test can therefore give a misleading picture of a sustained workload if it ignores credit behaviour. Record the instance's relevant configuration and observe a representative duration before drawing conclusions.

Horizontal scaling can distribute independent requests across application servers. However, each new server must run the right release, obtain the required configuration, connect to dependencies and be selected by the traffic distribution mechanism. Copying an AMI creates a starting environment; it does not automatically solve application state, consistency or traffic routing.

If the original server used ninety percent CPU, adding a second one does not guarantee that both settle at forty-five percent. Work may distribute unevenly, some work may be serial, and dependencies or coordination may introduce overhead. The useful question is whether the measured user-facing result improved under the same workload. State an estimated benefit as an estimate until you have tested it.

Different observations suggest different experiments
ObservationPossible experimentResult to compare
Working data does not fit comfortably in memoryMore suitable memory capacity and application tuningMemory pressure, errors and operation latency.
Independent application work saturates processing capacityAdditional compatible application instancesCompleted operations and latency across the group.
All workers wait for one slow queryInvestigate query plan, waits and database resourcesDependency time and end-to-end request improvement.
Demand is short but predictablePrepare sufficient capacity before the openingReadiness before demand and controlled retirement afterwards.

4. Make the application suitable for multiple copies

Suppose server A stores a student's login session only in its own memory. The next request reaches server B, which has never seen that session. The student may appear logged out even though both servers are healthy. Horizontal scaling has exposed an application assumption: the next request was expected to return to the same process.

Session design needs an explicit solution, such as an appropriate shared session service or a correctly designed signed-token approach. Sticky routing can direct related requests to a selected target, but it creates its own balancing and failure considerations. It does not make data stored only on that target durable when the target disappears.

Uploaded files are another common trap. If a student uploads a project document to one instance's local disk, another instance may not find it. Decide where shared and durable data belongs, how all application copies access it and which identity grants that access. Keep temporary working files separate from records that must survive instance replacement.

Database operations must remain correct when requests run concurrently. Two application instances can attempt to reserve the last seat at the same time. More servers improve available processing only if the application still enforces capacity and uniqueness correctly. Transactions and constraints belong in the scaling discussion because correctness must survive the increased concurrency.

Background work also needs coordination. If every new instance starts the same daily email job, scaling out can send duplicate messages. Use a job ownership or queue design appropriate to the application, with safe handling of repeated delivery. An instance lifecycle is not a reliable calendar for business work.

A practical preparation check is to replace an application instance in a test environment and verify login, uploads, reservations and background jobs. Record what lives outside the instance and what can be recreated. The aim is not to remove every bit of local state; it is to understand which state is temporary and which requires a deliberate sharing or recovery mechanism.

5. Read an Auto Scaling group's settings and actual state

An Auto Scaling group manages a collection of EC2 instances according to its configuration. It uses a launch template and related settings to create replacements or additional instances. The template version matters: a group using an older version may continue launching an earlier image even after someone creates a newer version of the template.

The group's minimum, desired and maximum capacities express its intended bounds and target. In a simple equal-instance example, minimum two, desired three and maximum six means the current target is three instances within the configured range. Other configurations can express capacity using weights, vCPUs or memory-related units. Always establish the unit before interpreting a capacity number as a server count.

Desired capacity is an intention, not a count of application servers already helping students. A group can desire three while one instance serves traffic, one initializes and another fails to launch. Investigate the scaling activity and instance states. Launch permissions, quotas, unavailable capacity, configuration errors and startup failures can all interfere with reaching useful capacity.

Even without a dynamic scaling policy, a group can maintain its desired capacity and replace instances it considers unhealthy. Attaching a load balancer and enabling the appropriate health-check integration are distinct configuration steps. A load balancer excluding a target and an Auto Scaling group replacing that target are related but separate decisions.

Maximum capacity is an important control, but it is not a hard total-bill limit or a universal promise about every transient instance count. Documented replacement, rebalancing and weighted-capacity behaviour can involve capacity beyond a simplistic interpretation of that number. Other services, storage and data transfer also contribute to cost. Use resource controls together with budget monitoring and ownership.

For a paper exercise, track five columns: desired, launched, initializing, healthy targets and useful completed operations. If desired increases from two to four, leave the healthy-target count unchanged until the supplied readiness event occurs. This small discipline prevents the common mistake of announcing that scaling solved an incident at the moment a launch request was accepted.

6. Read a metric and an alarm as different objects

A metric is a series of measurements with a defined meaning and identity. Before reading a graph, identify the metric name, namespace, dimensions, unit and time range. An instance CPU measurement and a group average answer different questions. Selecting the wrong dimension can make a perfectly functioning alarm watch the wrong resource.

A statistic summarises measurements for a period. Average CPU over five minutes is different from the highest observed value in that period. A brief spike can be diluted in the average. The period also differs from the frequency at which you happen to refresh the dashboard. Refreshing the browser every second does not create more detailed measurements.

Some observations require guest instrumentation. Memory use and filesystem free space are not supplied as ordinary standard EC2 metrics in the same way as the basic instance CPU metric. A configured CloudWatch agent or another approved collection mechanism can publish them. Verify that data is arriving under the expected dimensions before building an action around it.

An alarm evaluates measurements against a rule. Its configuration includes a comparison, threshold, period and evaluation requirements. In an M-out-of-N example, M is the number of breaching data points required among N evaluated points. A two-out-of-three rule can trigger with one non-breaching point between two breaches. A two-out-of-two rule requires both evaluated points to breach.

Specify the comparison exactly. Greater than seventy does not include exactly seventy. Also state whether seventy is an average, maximum or another statistic, and which resource it describes. Without these details, the sentence CPU crossed seventy is too vague to reproduce or diagnose the alarm.

CloudWatch alarm states include OK, ALARM and INSUFFICIENT_DATA. Missing observations are not automatically zero activity. Treatment of missing data and the evaluation window affect the outcome, and CloudWatch may retrieve additional data for evaluation. The worksheet below deliberately uses complete supplied windows; it does not reproduce every live evaluation rule.

An alarm rule covering two five-minute periods does not promise that useful capacity appears exactly ten minutes after a traffic surge begins. Measurement publication, evaluation, action execution, launch and readiness take time. Think of the response as a sequence of stages and measure it. That explains why predictable registration openings may need preparation before demand arrives.

7. Separate notification from capacity control

An SNS notification tells a recipient about an event. A scaling action requests a capacity change. They can be configured from the same alarm but are not the same action. Receiving an email proves something about the notification path; it does not prove a new instance launched, became healthy or accepted a registration.

For an SNS email subscription, the intended recipient must confirm the subscription before it receives topic messages. A topic existing in a console is not enough. In an authorised setup, verify the recipient, subscription status, topic permissions and the alarm's selected action. In this overview we only describe that process; the offline exercises send no email.

Alarm notifications normally follow state transitions. Auto Scaling actions have different repeat behaviour: CloudWatch can continue invoking them while an alarm remains in the relevant state. The resulting capacity change still depends on the scaling policy and group conditions. Do not teach one email per minute or one new instance per email as a universal relationship.

When investigating a failed response, follow the chain in order. Did the intended metric arrive? Did the alarm reach the expected state? Was the action configured and enabled? Did a scaling activity occur? Did the launch succeed? Did the instance become an eligible target? Did the application operation improve? Each answer determines the next check.

Give notifications enough context for a person to act: the resource, environment, symptom and relevant runbook. Avoid including secrets or full student records. A message that merely says high CPU leaves the recipient to discover the affected system before doing anything useful. Good alert design reduces that investigation delay.

8. Choose a policy that matches the workload

Manual scaling means a person deliberately changes the intended capacity. It is useful while learning the application or handling a known event, but someone must observe demand and act in time. A fixed desired capacity can still receive unhealthy-instance replacement; automatic replacement and automatic demand-based resizing are separate capabilities.

Scheduled scaling changes capacity at planned times. If registration opens at nine, a schedule can provide time for initialization before nine. The schedule needs the correct timezone and a plan for ending the event. A calendar action cannot know by itself that the college postponed the workshop, so ownership and review remain necessary.

Target tracking uses a suitable metric and target value to adjust capacity, with Auto Scaling managing the associated alarms. The metric must describe load in a way that responds appropriately to capacity changes. Requests per target can be more meaningful than total incoming requests, because the total can stay the same after adding servers while each server handles less work.

Do not directly edit the alarms managed by a target tracking policy as though they were independent manual alarms. Configure the policy through its intended controls. A target is an operating aim with discrete capacity choices and response delays, not a promise that the graph will remain exactly on one number every second.

Step scaling uses defined adjustment ranges in response to an alarm's degree of breach. It offers control over the size of the requested change at different levels. Simple scaling uses an adjustment with cooldown behaviour. Read the selected policy's rules rather than assuming every policy waits for the same delay or uses the same adjustment calculation.

Predictive scaling uses historical patterns to forecast capacity needs. It can help with recurring demand, while dynamic policies respond to observed changes. Its forecast-only mode lets you review predictions before enabling forecast-based scale-out. Predictive scaling does not itself scale in when its forecast falls; an appropriate additional policy handles that need. A forecast is not advance knowledge of every unexpected event.

Policy selection also includes a decision about scale-in. Removing capacity too eagerly can create oscillation: add, remove, discover overload and add again. Consider the application's startup time, variability and tolerance for interruption. Describe success in terms of stable service and sensible resource use, rather than the largest possible number of scaling events.

9. Give startup, health and metric timing separate names

A newly launched machine may need to start services, load configuration and establish dependencies. A readiness check asks whether it can perform the work required before accepting ordinary traffic. A process being alive is a narrower observation. Choose checks that are meaningful, bounded and appropriate for the architecture.

Instance warmup helps the scaling mechanism account for the time needed for usage to stabilise after an instance enters service. Startup work can temporarily distort CPU and other observations. The configured warmup affects how the group uses those observations and makes further scaling decisions. Measure initialization and stabilisation instead of copying an arbitrary value from a different application.

The health check grace period has a different purpose. It prevents premature unhealthy replacement of a newly in-service instance while applicable startup checks settle. It does not stop the load balancer from performing checks, and it does not make a broken application healthy. An excessively long grace period can also delay recognition of a genuine failure.

Cooldown is another separate concept, particularly relevant to simple scaling policies. It allows the effect of a scaling activity to be reflected before another simple scaling activity occurs. Do not describe it as a universal pause on every operation in the group. Read the policy-specific rules when combining manual actions, dynamic policies and lifecycle events.

A launch lifecycle hook can hold an instance in a lifecycle wait state while custom preparation completes. The automation handling the hook needs a completion or timeout outcome. A hook does not run your preparation correctly simply because it exists. Monitor it and make failure behaviour explicit so that unfinished instances do not accumulate without explanation.

Draw a timeline for your application: launch requested, operating system ready, application started, readiness passes, useful traffic begins and metrics stabilise. Attach the configured controls to the stages they influence. This exercise is more helpful than memorising three default numbers, because defaults can differ by interface and are not measurements of your application.

10. Remove capacity without abandoning the work it holds

Scaling out receives attention because it adds resources. Scaling in deserves equal care because it removes resources that may still be processing work. A student submitting a reservation should not lose the operation merely because average load fell. The retirement process needs to account for both new arrivals and work already accepted.

For an application behind an ALB, deregistration stops new requests being assigned to the retiring target while existing work has a configured opportunity to finish. The deregistration delay is bounded; it is not a promise that every arbitrarily long operation will complete. Application shutdown, request timeouts and job behaviour must fit the intended retirement process.

A termination lifecycle hook can support custom preparation such as preserving diagnostic information or coordinating a worker's departure. It needs a reliable handler and a defined timeout outcome. Do not use a hook as the only copy of important data. The application should already place durable records in the intended storage rather than depending on a last-second rescue from an instance.

Queue workers require a related but distinct plan. A worker may have accepted a job that has not completed. The queue and application need a way for unfinished work to become available again, and the operation must tolerate the delivery behaviour of the selected system. Removing workers without considering in-flight jobs can lose progress or cause duplicate side effects.

Deploying a new image through instance refresh is also a capacity transition. Review the selected replacement strategy, healthy-percentage settings, warmup, available headroom and rollback arrangements. A rolling replacement is not automatically interruption-free. A tiny group and unsuitable replacement preferences can leave insufficient serving capacity even though the refresh process is following its configuration.

For the workshop, verify one representative reservation during a controlled test transition, read it back and examine errors and latency. Check the retiring target's remaining work and the replacement's release identity. Accept the change only after the useful operation and expected resource state both pass. The order of operations supports availability, but application evidence establishes the result.

11. Handle the interval before extra capacity is ready

Reactive scaling takes time, so a sudden surge can arrive before a replacement or additional instance is useful. Keep enough operating headroom for the expected response interval where practical. For a predictable college opening, preparing capacity ahead of time can be more effective than waiting for students to experience a long queue.

Bounded queues and admission controls help prevent unlimited accumulation. A queue can absorb a temporary mismatch between arrivals and processing, but it does not make the work disappear. If arrivals remain above the sustained processing rate, the backlog keeps growing. Monitor queue age and completion rate as well as the number of queued items.

Backpressure means communicating or enforcing that a downstream component cannot accept unlimited work. The application might limit concurrent expensive reports or return a clear retryable response for a suitable operation. The policy should protect essential operations and explain the user-visible outcome. Simply allowing every request to wait indefinitely can consume resources that the service needs to recover.

Retries can amplify demand. If one failed request produces three immediate repeats from each client, a struggling system receives more work exactly when it has less capacity to handle it. Use bounded attempts, appropriate delays and randomisation where suitable, and ensure repeated operations have safe semantics. A retry is a new demand event, even when the user only pressed the button once.

Caching can reduce repeated work for suitable content, but freshness matters. A workshop description can often tolerate caching more easily than the authoritative decision about the last available seat. Define which data may be older and which operation must use current protected state. Performance improvements should preserve the meaning of the service.

These controls complement scaling. They also provide useful choices when the group reaches its intended limit, a dependency cannot expand or launch capacity is temporarily unavailable. A mature plan includes what the application does when more machines cannot be added, rather than treating every overload as a problem that can always be solved by another launch.

12. Run three small capacity and timing exercises

The following programs need Python 3. They operate only on supplied numbers and lists in memory. They make no network requests, use no AWS credentials and create no files. Run each complete block in Bash or Zsh, or copy the Python body into your usual interpreter. Their outputs are model results, not benchmark measurements or an implementation of AWS control algorithms.

Lab A: find the shared limit

Assume each fully ready application server handles forty of our identical fictional operations per second. The shared database supports ninety operations per second in this model, and demand is one hundred per second. Predict the useful completion rate with one, two, three and four application servers. Then run the calculation.

python3 - <<'PY'
demand = 100
per_server = 40
database_limit = 90
results = []
for ready_servers in (1, 2, 3, 4):
    application_capacity = ready_servers * per_server
    completed = min(demand, application_capacity, database_limit)
    pending_per_second = demand - completed
    results.append((ready_servers, completed, pending_per_second))
    print('ready, completed/s, pending/s:', results[-1])
assert results == [(1, 40, 60), (2, 80, 20), (3, 90, 10), (4, 90, 10)]
PY

The fourth server adds no useful throughput in this simplified calculation because the database limit is already lower than application capacity. Ten operations per second still accumulate if all arrivals are accepted. The exercise assumes identical independent work, perfect distribution and fixed capacities. Real measurements include variability and overhead, so the arithmetic is a reasoning aid rather than a production sizing formula.

Now change the database limit to one hundred and sixty on paper, keeping demand at one hundred. Three application servers can then satisfy the supplied demand in the model. Explain which assumption changed and why adding the fourth still does not increase completions beyond incoming demand. This prevents confusing unused capacity with failed capacity.

Lab B: distinguish two-out-of-three from consecutive breaches

Use the complete CPU observations sixty-five, seventy-two and sixty-eight. Apply a threshold strictly greater than seventy. Then compare a second window containing seventy-two, sixty-eight and seventy-five. This worksheet labels incomplete windows separately and deliberately does not fill missing values or imitate CloudWatch's wider evaluation rules.

python3 - <<'PY'
def supplied_window(values, required, threshold=70):
    if any(value is None for value in values):
        return 'INCOMPLETE WORKSHEET'
    return 'BREACH' if sum(value > threshold for value in values) >= required else 'CLEAR'
cases = [([65, 72, 68], 2), ([72, 68, 75], 2),
         ([68, 75], 2), ([70, 71], 2), ([75, None, 76], 2)]
answers = [supplied_window(values, required) for values, required in cases]
for case, answer in zip(cases, answers):
    print(case, answer)
assert answers == ['CLEAR', 'BREACH', 'CLEAR', 'CLEAR', 'INCOMPLETE WORKSHEET']
PY

The second three-point window breaches two-out-of-three despite the middle value being below the threshold. The two-point window sixty-eight and seventy-five does not breach two-out-of-two. Exactly seventy is not greater than seventy. For the incomplete window, investigate the actual alarm's missing-data treatment and evaluation rules; the worksheet has intentionally declined to invent an AWS state.

Lab C: count useful capacity after readiness

The group desires three instances. A is ready and healthy, B is still initializing, and C has failed its application check. Count useful targets, then update B after a successful check. Finally, remove A from new-work eligibility while it drains. This separates intended size, readiness and retirement using explicit supplied states.

python3 - <<'PY'
desired = 3
instances = {
    'A': {'ready': True, 'healthy': True, 'draining': False},
    'B': {'ready': False, 'healthy': True, 'draining': False},
    'C': {'ready': True, 'healthy': False, 'draining': False},
}
def eligible():
    return [name for name, state in instances.items()
            if state['ready'] and state['healthy'] and not state['draining']]
print('Desired:', desired, 'Eligible:', eligible())
assert eligible() == ['A']
instances['B']['ready'] = True
print('After B check:', eligible())
assert eligible() == ['A', 'B']
instances['A']['draining'] = True
print('New-work targets while A drains:', eligible())
assert eligible() == ['B']
PY

The final list does not claim that A has already terminated or completed every existing request. It only says that our model stops assigning new work there. AWS target and lifecycle states have their own rules, and this program does not send health checks or manage a load balancer. Use it to explain the observations you would need from a real deployment.

13. Write the operating note before changing capacity

Begin with the service and ownership: the registration application, its environment, the affected group and the person responsible for the event. Record the current launch template version and known working release. Keep the expected resource identities separate from example names used in teaching. An operating note must identify the actual intended system.

Next state the evidence and acceptance conditions. For example, the fictional goal might require the representative reservation to complete within an agreed duration with no unexpected failures at the planned demand. Include a readback check so that a fast response cannot hide a failed save. Record the workload and observation interval used to assess the result.

Describe the transition, not just the final number. Specify when additional instances should be ready, the evidence for readiness, the change's stopping condition and the plan if launch or dependency checks fail. For removal, account for new traffic, existing requests, background work and data ownership. Identify which settings or resources must be restored after a temporary event.

Close the note with observed results and remaining limitations. Compare useful capacity, latency, errors and retained resources with the plan. If the exercise is finished, inspect schedules and policies as well as instances so a forgotten action does not recreate temporary capacity later. Cleanup should follow the reviewed lab inventory, not a broad deletion of unfamiliar resources.

14. Interview questions with reasoning

1. The site is slow but CPU is low. Would adding instances help?

It might, but low CPU alone does not identify the problem. I would locate where requests wait: a database query, connection pool, storage operation or external service can limit progress. I would add capacity only with a reason to expect improvement and compare representative end-to-end results afterwards.

2. Describe vertical and horizontal scaling for this registration application.

Vertical scaling changes the capabilities of an application component, such as choosing more suitable memory for an instance. Horizontal scaling adds application copies that can share requests. The latter also requires correct session, file and database behaviour across copies. Neither change promises a fixed proportional performance improvement.

3. Desired capacity is four, but only two targets are useful. Is Auto Scaling finished?

No. Desired is the target state. I would inspect launch activities, lifecycle states, initialization and health checks to account for the other capacity. The application must be ready and correctly routed before it contributes useful service. An accepted capacity request is not evidence that students can already use it.

4. What does a two-out-of-three alarm rule mean?

Two evaluated data points must breach among three evaluated points, according to the metric, statistic, comparison and window configuration. The breaches need not be consecutive in a complete three-point example. Missing data requires its configured treatment and actual service rules; it must not be silently substituted with zero.

5. Explain warmup, grace period and cooldown without combining them.

Warmup helps account for a new instance's initialization and metric stabilisation in scaling decisions. The grace period protects a newly in-service instance from premature unhealthy replacement under applicable checks. Cooldown concerns spacing relevant scaling activity, particularly simple scaling. They address different decisions and must be configured from the application's behaviour.

6. Why can a group need more instances even after a notification email arrives?

The email reports an event through a notification path. Capacity control is a separate action, followed by launch and readiness. I would examine each stage rather than assume email delivery means the incident is fixed. The final evidence is useful application performance and correctness under the relevant demand.

7. Does a maximum capacity of six cap the whole AWS bill?

No. It controls the group's intended scaling range in its configured units, with documented lifecycle and weighted-capacity behaviour to consider. Charges can also come from other resources and retained storage. Budget monitoring, resource inventory and ownership complement capacity settings; none should be confused with the others.

8. What would you verify before scaling in?

I would confirm that remaining useful capacity can handle demand, that new work stops going to the retiring target appropriately, and that accepted requests or jobs are handled through the designed retirement process. I would then check errors, latency and representative saved results. A lower instance count alone is not a successful outcome.

15. Answer the scenario before revealing the explanation

1. Four ready servers offer 160 model operations per second, but the shared database offers 90. Can this path complete 160?

Not under the supplied assumptions. The shared dependency limits useful throughput to ninety. Investigate that constraint and the workload before adding another application server. Also remember that this minimum-of-capacities model omits variability and coordination costs present in a real system.

2. Values are 72, 68 and 75. Does greater-than-70 for two out of three breach?

Yes, in this complete supplied window. Seventy-two and seventy-five both breach, even though they are separated by sixty-eight. A requirement for two consecutive evaluated points would be a different rule. Always read the configured evaluation requirement as well as the threshold.

3. Registration starts at nine, and startup takes several minutes. Is a nine o'clock launch necessarily early enough?

No. Launch time and readiness time differ. Plan preparation with sufficient lead time for the measured stages and account for possible delays. A schedule expresses when an action should occur, not a guarantee that all application checks finish at that same instant.

4. The new server has the correct image but cannot find uploaded documents. Which assumption should you inspect?

Inspect file placement and access. The old server may have stored uploads only on local storage. An image or application copy does not automatically provide shared current documents. Identify the durable storage design and verify access from every intended application copy.

5. A target is draining. Should we assume it has no unfinished work?

No. Draining describes a transition intended to stop assigning new work while allowing existing work a bounded opportunity to finish. Check the actual lifecycle and application evidence. Do not confuse exclusion from new-work selection with completed termination or a guarantee that every request succeeded.

16. Revision cards

Demand and throughput

Arrivals and completions are different measurements. When accepted arrivals exceed sustainable completions, unfinished work accumulates. Track waiting time and failure behaviour alongside the resource graph.

Useful capacity

A machine contributes only when the application is ready, reachable and suitable for the operation. Desired, launched and healthy serving capacity should be observed separately.

Metric identity

Name the resource dimensions, unit, statistic and period before interpreting a value. A precise alarm rule must also specify its comparison and evaluation requirements.

Application state

Sessions, uploaded files, reservations and background jobs need deliberate handling across copies. More processors do not repair assumptions that all requests reach the same process.

Time to help

Detection, action, launch, initialization and readiness each contribute to response time. Prepare for predictable demand and measure the stages instead of assuming scaling is instantaneous.

Controlled retirement

Scale-in removes a participant that may still own work. Coordinate new-request routing, in-flight operations and durable data before accepting the resulting smaller group.

17. Tasks for your learning notebook

  1. Diagnose a supplied incident. Describe a slow reservation with low application CPU and long database waits. State two useful next observations and explain why adding web servers is only a hypothesis.
  2. Complete the capacity table. Recalculate Lab A after changing demand and the database limit. State each assumption and identify the stage that limits each row. Do the arithmetic before running a modified model.
  3. Design an alarm on paper. Specify a fictional metric identity, statistic, period, threshold, comparison and M-out-of-N requirement. Include a deliberate missing-data case and explain what extra configuration you need to interpret it.
  4. Rehearse the opening timeline. Draw initialization, health checks, traffic eligibility and stable metrics before a nine o'clock event. Mark which times are supplied assumptions and which you would measure in a real authorised environment.
  5. Review scale-in. Explain the fate of a reservation request, an uploaded file and a background job on a retiring instance. Your answer should identify the storage and coordination mechanisms that preserve each important outcome.

Official references

Use these primary sources for current service behaviour. The supplied arithmetic, examples and programs are original teaching models and do not promise production capacity or availability.

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

London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. These are browser-only answer exercises for the fictional scenario. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 10

Easy Describe an Auto Scaling group

See current instances and sizes of the group.

Describe the Auto Scaling group londonlegal-asg.

  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 Change desired capacity

Before a big sale, raise desired capacity so servers are ready in time.

Set the desired capacity of londonlegal-asg to 4.

  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 Change min and max size

Minimum and maximum bound intended group capacity. They do not guarantee application availability or cap every charge.

Update londonlegal-asg to min 1 and max 10.

  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

Inspect target health, response status and load-balancer logs together; an unhealthy-target observation does not uniquely determine one HTTP error.

Show the health of the targets in arn:aws:elasticloadbalancing:eu-west-2:114543297314:targetgroup/londonlegal-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 Kubernetes LoadBalancer Service

A Service of type LoadBalancer relies on the installed cloud integration or controller and its configuration to provision the intended load balancer.

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.

Hard Create an Auto Scaling group

Min, max and desired decide how many servers run; the group replaces unhealthy ones.

Create ASG londonlegal-asg from launch template londonlegal-lt with min 2, max 6, desired 2, in subnets subnet-0145432db314bb1,subnet-045432db314bb2.

  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 launch template

The launch template is the recipe Auto Scaling uses to build each new server.

Create launch template londonlegal-lt using the settings in lt.json.

  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 Roll out a new AMI with instance refresh

A rolling instance refresh replaces instances according to configured health and capacity preferences. Availability still depends on those settings and the application.

Start an instance refresh on londonlegal-asg.

  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. Special deployment types have separate requirements.

Create an ALB named londonlegal-alb in subnets subnet-0145432db314bb1 and subnet-045432db314bb2 with security group sg-0145432ca3144c3b2.

  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 is what accepts traffic on a port and forwards it to a target group.

On load balancer arn:aws:elasticloadbalancing:eu-west-2:114543297314:loadbalancer/app/londonlegal-alb/50dc6c495c0c9188, create an HTTP listener on port 80 that forwards to arn:aws:elasticloadbalancing:eu-west-2:114543297314:targetgroup/londonlegal-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.