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

Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)

AWS Cloud

10.1 Why and what

Friends, static files can cover the dairy's notices. Saving customer orders needs application logic and a persistent store, such as a database. Let's first understand what changes when the server builds a response from request inputs or current data.

A dynamic response is generated at request time by application code. The code might read a database, call a service or calculate from input. Some websites serve a mixture of static files and dynamic responses, including views that vary by user.

                    3-tier architecture on a single EC2 instance
 Browser ──HTTP:80──► [ Web tier ]  Nginx / Apache (reverse proxy, static files)
                            │
                            ▼  FastCGI socket / HTTP 127.0.0.1:3000 or :5000
                      [ App tier ]  PHP-FPM  |  Gunicorn + Flask  |  Node + Express
                            │
                            ▼  TCP 127.0.0.1:3306 or unix socket
                      [ Data tier ] MySQL / MariaDB  (private in this example)
Language App server / runtime How the web server talks to it Process manager
PHP PHP-FPM (FastCGI Process Manager) or Apache mod_php PHP-FPM uses FastCGI over a Unix socket or TCP. With mod_php, Apache invokes its own PHP handler. Manage the chosen FPM service or Apache process under its distribution’s service manager.
Python (Flask/Django) Gunicorn (WSGI server) HTTP reverse proxy to 127.0.0.1:5000 systemd unit
Node.js (Express) Node itself HTTP reverse proxy to 127.0.0.1:3000 pm2 or systemd unit

Why a reverse proxy?

A front web server can handle TLS, approved public listeners, static files and forwarding to the right app. This separates those jobs from the application’s runtime. Some platforms provide the same front-layer responsibilities through a managed endpoint.

Ravindra Bagale's Tip

For this one-host lab, bind HTTP app processes to the loopback interface or use their approved sockets. Expose only the intended front door. If app and data services run separately, use the approved private connection and restrict access to their expected clients.

Lab

Chala, Mauli Dairy chya order system sathi kagdavar teen tiers kadha: web, app aani data. Pratyek tier samor software (udaharan Nginx, Gunicorn, MariaDB), port aani te internet la disel ki nahi te liha.

Choose dynamic hosting when the answer depends on current information

The campus supply desk starts with a small page that tells students when notebooks are available for pickup. A volunteer edits the count in an HTML file each morning. By midday another volunteer has distributed some notebooks and changed the office spreadsheet, but the published page still advertises the morning count. The code needed to show a header and opening hours is simple. The missing ability is to read the current approved stock record when a student asks for it. That is a practical reason to introduce a dynamic response.

A static server can send an already published file without running stock rules. An application can instead read the request, look up a current value and build the response from the result. The browser still receives ordinary HTTP. The extra work happens inside the path that generated its response. In this lesson compare a printed snapshot with a live stock endpoint. Then follow what would change when deploying the application's web server, runtime and database on an assigned EC2 host.

This does not mean every page needs a database or that anything with JavaScript is dynamic on the server. You can use static files for the opening notice and a small API for a value that should come from the stock table. An API is a defined way for another program to request a service or exchange information, for example a browser asking for JSON at a stock URL. Start by choosing which answers must reflect information that can change independently of the last public file deployment.

Compare a static notice, a snapshot and a current result

Imagine three links on the campus page. The opening hours change only when the building schedule changes. The morning stock sheet represents the officer's last published snapshot. The stock search should check the current row when it receives an item code. The first two are reasonable static files because they promise a particular published version. The last answer is a function of application logic and current data. It can change while the public HTML and CSS still have the same bytes.

Choose how to produce each supply desk response
What a reader requestsInputs that determine the answerPossible implementation
Opening-hours notice.The last approved published file.Serve the HTML from the site's public release.
Stock sheet from the morning review.Recorded snapshot time and values chosen at publication.Publish a generated HTML or CSV file labelled with its date.
Current availability for an approved item.Validated item code and the current stored row at request time.Route the request to the runtime and return JSON or render an HTML view.
A staff member's stock adjustment.Identity, permission, input rules and the current data transaction.Run an authorized write operation and verify the resulting stored state.

The third link can coexist with static assets on the same site. When a student clicks it, a browser script may request JSON and display the result inside the file-based HTML. JSON is a text format that represents values such as names, quantities and lists. The JavaScript executes in the browser; the application endpoint executes on the server and receives only what the client sends in the request. In a server-rendered alternative the runtime could read the same data and build an HTML document directly. Follow which component actually produced each byte to understand the deployment.

A database is often useful because multiple operations can read and update shared structured state across requests. It is not required for every dynamic response. An application can calculate a shipping estimate from a submitted value, call a different service or format the time without storing a database row. Likewise a static page can be generated from database records overnight and served as a snapshot during the day. The deciding question is when and where the answer was produced. Use the desired freshness, privacy and operation to choose the architecture.

Start with a precise contract for one request

For this exercise use GET /api/stock?sku=NOTEBOOK. GET requests a representation. The portion before the question mark is the path the application routes. The query parameter provides the stock key to look up. The server should decide whether that key is recognized, read the current row and return its quantity. The success response should be JSON and identify the item it actually looked up. The web server can also directly serve /notice.html with a fixed snapshot that clearly states when it was taken.

A contract states what input is supported and what the outcome means. In the fixture the valid example codes are NOTEBOOK and PENCIL. An approved code without a stored record will produce 404. Missing, repeated or unsupported input will produce 400. If the storage path is deliberately unavailable in the exercise, the application responds with a small 503 body without exposing the local error detail. A valid request that returns zero is a different outcome from a missing row. Zero means the item record exists and there are no units left.

Distinguish what this operation reads from anything that changes state. A GET stock request should not decrement the count just because a student checks it. A reservation or adjustment could be a POST under a separate policy. It would need server-side input validation, authorization and a transaction that confirms the requested operation can be applied. One successful read does not guarantee stock will still be available when a later reservation is made. Another client can change the state between those requests. Design reservation rules and confirmations based on that workflow.

Define which information is public. The demonstration returns a code and a count from synthetic stock. A real supply desk might expose only an availability category rather than raw quantities, or might limit the endpoint to authorized students. The HTTP route identifier and button displayed by the browser do not establish permission. Validate the request and enforce access at the component that performs the operation, including for a request sent directly to the endpoint. The lab deliberately contains no real student names, purchase records, authentication tokens or personally identifying details.

Follow the browser, front web server, application and database

Begin with one student's request for the notebook count. The browser first locates and connects to the approved site's front door, usually over HTTPS for a live service. The web server reads the host and path. It can serve known static files directly and send /api/stock to the application through the configured interface. An application route handler validates the query parameter and asks the data store for matching information. It formats the response, and the front door returns the result to the browser. The browser never needs a direct database connection for this design.

  1. The client makes an HTTP request. Its URL identifies the intended host, route and the public stock code.

  2. The front web layer selects the site and either reads a public file or routes to its configured runtime.

  3. The application validates the requested code and uses a stored query to decide which row is relevant.

  4. The data store returns a matching row or no result according to the current data and connection policy.

  5. The application generates a representation with the agreed HTTP status and sends it back through the front layer.

These are logical responsibilities. A single instance can run all three with different processes and local connections. Another deployment can put the application and database on different machines or use a managed database endpoint in a private network. The address and access rules change with the placement. A loopback address such as 127.0.0.1 names the caller's own network environment, so a separate application machine or container cannot use it to reach a different database simply because both are part of the same logical application. Use the address or socket approved for their actual arrangement.

The boundaries help an operator investigate one failure. When the front server returns the correct static notice and the stock request is unavailable, the socket and ordinary static mapping have passed one test. The application route, dependencies or proxy mapping still need examination. If the same application request succeeds directly on loopback and fails through the front door, compare what it received at each path. The intended route and actual server's output tell you more than a single statement that the machine is running.

Use the protocol supported by the application runtime

A runtime provides the environment needed to execute your application code. An application server, module or adapter accepts requests and calls that code according to its interface. A proxy forwards requests to another service, often over HTTP. PHP can run separately in a PHP-FPM process that receives FastCGI instructions from a configured web server, with a Unix socket or a TCP connection depending on setup. Apache can also use a PHP handler module in a supported deployment. In that latter arrangement the module executes within Apache's process model, without a separate FastCGI hop for those requests.

Flask defines routes in Python. In a typical production setup a WSGI server such as Gunicorn accepts requests and invokes the Flask application through the WSGI Python server interface, while a front door can speak ordinary HTTP to its listening address. Express defines routing and middleware for a Node.js HTTP application. The Node process can listen on a local port and a front proxy can send HTTP to it. The protocol and listener must agree on both sides. A Unix socket is a local endpoint for processes and can still carry different protocols. Its path does not tell you what should be sent through it.

Check the deployed interface rather than guessing from a language name
Application setupFront-to-application interfaceIndependent verification
PHP with PHP-FPMFastCGI over an approved local socket or TCP.Inspect the configured FPM listener and an actual PHP response through the site.
PHP loaded into ApacheApache's configured handler for the PHP file.Verify its module or handler and the expected response content.
Flask with GunicornHTTP to the WSGI server, which calls the Python application.Request the application listener and compare through the front route.
Node with ExpressHTTP to a managed Node process.Match the actual binding, route and process logs.

Record who keeps the process alive after you log out. Running an app in one terminal is a useful development test. A managed service or deployment platform should own the approved production lifecycle, startup environment, ordinary run identity and crash visibility. Some runtimes or frameworks provide a development server that is not intended for public deployment. A production setup can use a front tier for TLS, public network listening, static assets and controlled forwarding. Whether you run a separate proxy depends on the chosen platform and its responsibilities, not a universal claim that the runtime cannot serve any of those features.

Design the data lookup before writing the response format

Decide what makes one stock record unique. The fixture uses an item code as the table's key and a nonnegative integer for the available quantity. A key identifies one row. A constraint is a rule the database checks when a write attempts to change its data. The example requires a quantity and rejects values below zero. A real warehouse can have the same item in more than one room. Its key or accompanying table would need to represent the item and location according to the service rules. Pick a simple shape that matches the experiment rather than relying on a filename or display name to identify every record.

In the application, validate the stock code and pass it to a parameterized query. The query statement expresses the operation and the driver receives the submitted item as a separate value. This preserves the planned query structure and gives the engine a value to compare. The read endpoint still checks the authorized list of identifiers. Parameterization handles data in the query, while validation and authorization decide which values or operations make sense in the application. They solve different parts of the same request.

A pure read does not require permission to modify inventory. Where a database server supports separate users and grants, give the application only the required access. For a file-based demonstration, use a read-only connection for the HTTP handler, and make the synthetic update separately through a training writer. When later lessons move to MySQL or MariaDB, the driver and authentication, socket or network connections, and grant surface change. The observation that a query uses current state carries over. SQLite is a local embedded engine and is not an installation of either database server.

When designing a real write, think about where success becomes visible. A transaction collects changes into an operation that the database commits or rolls back. A response for an applied stock adjustment should reflect the resulting committed state. Returning a success page before storage succeeds can tell users an order was recorded while leaving no matching row. A production service also needs a plan for unknown outcomes after client retries, especially if they could repeat a stock adjustment. This lesson uses a read-only endpoint to keep that additional workflow separate.

Decide when the displayed answer needs to be fresh

A dynamic endpoint can still use caching, and a static object can be refreshed whenever the publisher replaces its bytes. The crucial question is what the service promises. For the supply desk, the HTML snapshot represents one known observation from earlier. It is valid as a snapshot when labelled clearly. The API example promises a read of the current committed row at the time of the request. The local fixture includes a response policy that prohibits caches from storing its JSON, making the exercise easier to observe directly.

In a real public service you might intentionally cache a stock response for a few seconds or serve a less precise availability band. That design needs an explicit accuracy target and cache scope. Shared caches can be useful for public values. User-specific details require an appropriate private or no-store policy and trusted handling of responses. Follow the actual HTTP cache directives and application behaviour. “The page is dynamic” does not automatically mean every browser sees a fresh database read. “The page is static” does not necessarily mean the bytes will stay the same forever.

Record the observed display and data update independently. If the database has the current count but a browser still shows the old figure, check whether that value came from the snapshot, API or cached front door. Inspect the response's path, type and headers instead of repeatedly changing rows. A browser script may fail to replace a default label after a failed API request. The page can look healthy while its dependency is unavailable. The acceptance criteria should separately require the static shell and the current data response to show the intended state.

Lab one. Compare an immutable file with a database-backed response

Use Python 3 with the standard sqlite3 module. The exercise opens a temporary file database and a loopback HTTP server on a high port selected by the operating system. It publishes only a synthetic HTML notice and implements a small stock route. Run it as a regular user and keep it local. Python's small built-in HTTP server here is a teaching harness. The later PHP, Flask and Node lessons cover runtimes intended for managed deployments.

python3 - <<'PY'
from contextlib import closing
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from tempfile import TemporaryDirectory
from threading import Thread
from urllib.parse import parse_qs, urlsplit
import json
import sqlite3

with TemporaryDirectory(prefix="supply-stock-") as area:
    folder = Path(area)
    database = folder / "stock.db"
    notice = folder / "notice.html"
    notice.write_text("<h1>Morning snapshot: 8 notebooks</h1>\n", encoding="utf-8")
    with closing(sqlite3.connect(database)) as db:
        db.execute("""CREATE TABLE stock (
            sku TEXT PRIMARY KEY,
            quantity INTEGER NOT NULL CHECK (typeof(quantity) = 'integer' AND quantity >= 0)
        )""")
        db.execute("INSERT INTO stock (sku, quantity) VALUES (?, ?)", ("NOTEBOOK", 8))
        db.commit()

    class Supply(BaseHTTPRequestHandler):
        def send_payload(self, status, body, media):
            self.send_response(status)
            self.send_header("Content-Type", media)
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def send_json(self, status, data):
            self.send_response(status)
            payload = json.dumps(data).encode("utf-8")
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(payload)))
            self.send_header("Cache-Control", "no-store")
            self.end_headers()
            self.wfile.write(payload)

        def do_GET(self):
            parsed = urlsplit(self.path)
            if parsed.path == "/notice.html":
                self.send_payload(200, notice.read_bytes(), "text/html; charset=utf-8")
                return
            if parsed.path != "/api/stock":
                self.send_json(404, {"error": "unknown route"})
                return
            args = parse_qs(parsed.query, keep_blank_values=True)
            items = args.get("sku", [])
            if len(items) != 1 or items[0] not in {"NOTEBOOK", "PENCIL"}:
                self.send_json(400, {"error": "provide one supported sku"})
                return
            sku = items[0]
            try:
                with closing(sqlite3.connect(database.as_uri() + "?mode=ro", uri=True)) as db:
                    row = db.execute(
                        "SELECT quantity FROM stock WHERE sku = ?", (sku,)
                    ).fetchone()
            except sqlite3.OperationalError:
                self.send_json(503, {"error": "stock temporarily unavailable"})
                return
            if row is None:
                self.send_json(404, {"error": "stock item not registered"})
                return
            self.send_json(200, {"sku": sku, "quantity": row[0]})

        def log_message(self, format, *args):
            pass

    with ThreadingHTTPServer(("127.0.0.1", 0), Supply) as site:
        thread = Thread(target=site.serve_forever, daemon=True)
        thread.start()

        def request(path):
            conn = HTTPConnection("127.0.0.1", site.server_port, timeout=3)
            try:
                conn.request("GET", path)
                response = conn.getresponse()
                return response.status, response.getheader("Content-Type"), response.read()
            finally:
                conn.close()

        try:
            before = request("/notice.html")
            current = request("/api/stock?sku=NOTEBOOK")
            assert current[0:2] == (200, "application/json")
            assert json.loads(current[2])["quantity"] == 8
            print("initial stock", current[2].decode())
            with closing(sqlite3.connect(database)) as writer:
                writer.execute("UPDATE stock SET quantity = ? WHERE sku = ?", (3, "NOTEBOOK"))
                writer.commit()
            updated = request("/api/stock?sku=NOTEBOOK")
            assert updated[0] == 200 and json.loads(updated[2])["quantity"] == 3
            print("updated stock", updated[2].decode())
            assert request("/notice.html") == before
            print("unchanged snapshot:", before[2].decode().strip())
            assert request("/api/stock?sku=PENCIL")[0] == 404
            assert request("/api/stock?sku=NOTEBOOK&sku=PENCIL")[0] == 400
            saved = folder / "temporarily-held.db"
            database.rename(saved)
            try:
                assert request("/api/stock?sku=NOTEBOOK")[0] == 503
                assert request("/notice.html") == before
                print("dependency unavailable: stock 503, notice still 200")
            finally:
                saved.rename(database)
            assert request("/api/stock?sku=NOTEBOOK")[0] == 200
        finally:
            site.shutdown()
            thread.join(timeout=5)
PY

The first stock response shows eight, and the second shows three after the separate writer commits an update. The exact static page response remains unchanged throughout. The missing item and invalid repeated-input assertions verify two independent failure outcomes. Temporarily moving the synthetic database causes the read to fail without creating a replacement database, because the handler requested read-only mode. During that failure the static notice still responds. Restoring the original database makes the current stock route pass again.

Read the test as a set of causal claims. The client made exactly the same stock request before and after a database write. The input stayed fixed. The application used the new committed value, and the unchanged notice proves the test did not deploy a new HTML release. When the data dependency became unavailable, the app returned a bounded response rather than sending a database exception to the reader. The example shuts down its local listener and removes the synthetic database, notice and scratch directory automatically. No cloud database, package service or proxy was involved.

Lab two. Map the prototype to an assigned managed service

Use the successful local outputs or the written contract from the first lab. Draw three boxes for the web layer, runtime and data layer. If your assigned design puts all three on one VM, label the front listening address and the runtime's actual upstream interface. Add the local database socket or address if one is planned. If the data layer is separate, replace the local address from the drawing with the approved private database endpoint and the expected client identity and transport. The shape of the request doesn't require all three services to share a network address.

  1. Write down two requests that deliberately exercise different components. For example, a notice file can be a front-layer control and the stock route can test the runtime plus a specific read.

  2. Mark which component validates user input, selects the query and turns its result into the final representation. Add where the controlled lab writer commits an update and how another request can observe it.

  3. Decide which transport and service names apply to your selected runtime. For PHP-FPM, label FastCGI rather than ordinary HTTP. For an HTTP application listener, label its actual local address or permitted private connection.

  4. Check what evidence would distinguish a route error from a dependency error. Include one direct app check when the interface permits it and one ordinary request through the intended front layer.

A complete sketch names both sides of each connection and explains the success check. A diagram with the word “database” next to the browser, or 127.0.0.1 for a separate database guest, needs correction. Put credentials and private network access under the designated component's ownership. Keep the front-door and database connectivity decisions independent. When this is a paper lab, there are no cloud resources to clean up. If an authorized managed test follows, limit it to the assigned deployment and verify its service and resource cleanup separately.

Send an honest result for each dependency state

Some beginners put “No stock” on a page whenever the application cannot read the database. That makes a genuine quantity of zero indistinguishable from a temporary service failure. Choose outcomes that reflect each case. A successful lookup can use 200 and carry the integer zero. An unsupported query can use 400. An approved item absent from the catalog can use a defined 404 response. An unavailable dependency can lead to an application-specific temporary response such as 503. A front proxy may instead return a gateway error if it cannot obtain a usable response from the application at all.

Compare the intended response with what actually failed
Observed resultWhat happened in this exerciseNext useful check
200 and quantity 0.The item exists and the query returned zero.Confirm the data and display do not combine zero with a missing result.
400 and invalid input message.The application declined the input before reading stock.Compare the exact query values with the public route contract.
404 and item absent.The accepted code did not match a stored row.Compare the intended code and database record. Distinguish the route-not-found response.
503 and temporary stock message.The prototype could not use its configured data dependency.Check the backend event and whether the authorized database is available.
Gateway error at a front proxy.The front door could not use the configured upstream response.Inspect proxy route, protocol, upstream listener and component logs.

Consider a real deployment where the opening notice succeeds at the public URL and the stock route returns the generic request message. Ask who generated that message. An Nginx error and an application JSON error can have different meaning even when both indicate a server-side failure. The route-level logs and returned media type may identify the producer. If you can make an approved direct request to the app's real HTTP listener, compare its output to the proxied one. For FastCGI, use the configured PHP route through the web server or an appropriate interface check, since a plain HTTP request to an FPM socket does not exercise its normal operation.

Write possible database detail into controlled application or database logs rather than the public JSON response. A read failure can reveal filenames or settings valuable to an operator but unnecessary for a student reading stock. Pass an appropriate correlation value between cooperating components if the deployment uses one, so an owner can identify the request in the logs. Treat client-supplied headers as data according to the front door's documented policy. Troubleshooting should establish the reason for the route's result without exposing database credentials, private configuration or unrelated user records.

Plan distinct environment settings for the application and its storage

The same stock lookup code can run locally and in a managed deployment. Its configuration answers questions such as which database to use, which app address and port to bind, and which trusted environment supplies credentials. For the SQLite fixture the database location is a generated scratch path. A MySQL or MariaDB service needs an approved connection setting, ordinary connection privileges, and any required TLS trust. Do not commit the real private credentials to the code or expose them through the public release. Provide them through an approved service configuration or secret-store integration and verify how the process receives them.

For one-VM exercises, the app or database can use a suitable private Unix socket or explicitly configured loopback address when it is only meant for same-host clients. The front door's listener provides public access only when needed. A container can have its own network namespace, so binding a process or attempting a connection to 127.0.0.1 applies inside that namespace. Separate hosting can use a private connection between application and database and narrow network rules for authorized clients. A wider local bind is not by itself authorization for public access. Match each listener to its required connection and applicable controls.

Compare application process lifetime with the data lifecycle. Updating a release changes code and its dependencies. Restarting the process might be part of adopting that code. The current stock table typically must survive the restart and be stored outside an ephemeral app release. A schema migration that adds or changes a data field has separate permissions and backout concerns. In the simple fixture the test data vanishes with its scratch directory. In a real service decide what must be retained, which operation backs it up and how you will restore or verify it independently from application deployment.

Specify the checks for a first managed launch

Start with three short checks. First obtain the correct static notice through the intended normal URL. Then ask the app for one known stock record and compare the expected code, response type and count. Finally verify an approved data refresh with a controlled test item, or observe a known update performed by its designated owner. If the newly available count reaches the app but the static snapshot remains unchanged, that can be the intended difference. Use active service logs and database records as support for those checks.

Keep basic health separate from the business operation. An application can listen and reply “ready” to a lightweight path while its stock query fails. The real process checker may intentionally avoid a database dependency to answer only whether the service responds. A readiness policy can check dependencies when the deployment wants to direct normal traffic only to ready targets. Define what an individual check covers. Keep one ordinary stock request in the acceptance suite because it exercises actual selected credentials, routing and query work.

Dynamic serving introduces work per request. Each request can use process time and a database connection. A burst of readers may affect the number of application workers and the time queries take. Connection reuse can limit connection setup overhead, but an oversized pool per process can exceed database limits when the application scales. For a first deployment record expected traffic, permitted resources, and which stage would show waiting or errors. Design changes should reflect measured symptoms and the actual product requirements rather than guesses based only on the language.

For maintenance, keep the exact code release, storage settings and relevant network paths on the deployment record. Back up what needs rollback under the owner's policy and test the queries after changing the runtime. If you later replace the front door, check what paths it serves directly and what protocols it uses upstream. For any authorized cleanup remove only the synthetic changes and resources created for the exercise. The mechanism learned here is the ability to follow one request through independent responsibilities and identify which component's output needs correction.

Choose who turns current data into what the reader sees

The dynamic response can be almost the same story with two different interfaces. In the server-rendered version the application reads the row and puts the count into an HTML template before replying. In the version driven by browser code the application returns JSON and the page's script chooses how to display it. Both start with the same authorized read. The client-server design shifts which component builds the visible part of the response. Verify the data and the rendered experience according to that choice.

Consider how a new stock field is introduced. If the server renders it directly, review its template, value formatting and safe treatment of text before the next release. If a browser calls the API, confirm both components agree on the field name, allowed values and how an unavailable response should look. A response can be technically successful while the client expects a different field and leaves the display blank. Prepare an acceptance example with the exact JSON fields or expected visible label and check it through the real public route.

Write response values with the formatting appropriate to their destination. A JSON serializer can encode a structured payload, while an HTML template requires safe treatment for its output context. Binding a value to a SQL query answers a different problem from rendering that result in HTML. The lab only serializes controlled public numbers and identifiers. A real system should validate data and encode its presentation without exposing internal database records or error details. Describe each boundary as an independent responsibility when reviewing application design.

Trace a stock refresh from update to browser

Suppose the teacher offers a new stock count of zero for the exercise. The stored row remains present. Follow its path from the approved writer through commit to another connection's read, then through JSON serialization to the browser label. The result should indicate an existing item with no units, not the unknown-item outcome. A separate approved item with no record demonstrates that state. A temporarily unavailable store demonstrates that the status for server failure should also differ. Use such distinct cases to make the endpoint's meaning explicit before deploying it.

A read represents the data observed by that query. Another operation may adjust the same item before the next request. A client that leaves a tab open can still display an earlier observation until it requests another value. Policy should determine whether the page needs to display when the count was read, when to refresh and what to show if the refresh fails. The course fixture proves the changed value from a deliberately repeated request. It does not create a continual availability guarantee.

Compare the response to a separate approved writer's expected value without giving the HTTP client's route permission to change it. In production a staff update would require its own identity, validation and audit record. If the current quantity changes unexpectedly, compare the authorized data update and app query with the client display before replacing the public files. This is the operational difference the exercise is meant to reveal. A public snapshot and a live data route need independent acceptance and owners.

Use names that identify the route and data scope

Write the stock API path, the parameter name and one expected synthetic record in the operating note. A front route might remove or retain a prefix before forwarding the request. If an app reports an unknown path, compare the request it received with that contract. Changing the database would not correct a route that never entered the stock handler.

Interview questions with explained answers

What makes a server response dynamic?

The application generates it by applying code to inputs at request time. It may read a database or another service, but the defining behaviour is the request-time decision. The same request can return a changed stock quantity after a data update without a new HTML deployment.

Does JavaScript in a static file make the server's page generation dynamic?

Browser JavaScript can make the displayed page interactive. The server can still deliver the HTML and script as prepared files. A separate API requested by the script can be dynamic.

Why can three tiers run on one EC2 instance?

The web, app and data responsibilities describe roles. Multiple processes or handlers can carry them out on one host with local interfaces. Separate placement changes addresses and access rules without changing those responsibilities.

How do you know that a successful page actually read current data?

Test the data-backed route for a deliberate reference value and a controlled approved change. Compare its response after commit with the expected actual row and keep the independent static page as a control.

Why is HTTP unsuitable for a PHP-FPM FastCGI socket?

The socket identifies a communication endpoint. PHP-FPM expects its specific FastCGI request protocol. A web server with the correct handler constructs that request. An HTTP app uses a different upstream interface.

Check your understanding

  1. The morning HTML says eight notebooks. The stock route reports three. Which can be correct?

    Show answer

    Both can meet their stated contracts. The HTML is a labelled snapshot and the route reads the current committed result.

  2. The database gives no row for an approved item. Why shouldn't the app display zero automatically?

    Show answer

    Zero is a stored quantity for an existing row. A missing row represents a different condition and needs its own application result.

  3. Does the site need to run a database on the request path to build a dynamic estimate?

    Show answer

    It can calculate a response from the request without a database. The runtime still generates the answer during that request.

  4. Why did the missing temporary database yield 503 while the notice kept working?

    Show answer

    The stock route depends on a configured read from the database. The file route reads the notice bytes independently.

  5. Can the app use 127.0.0.1 to reach a database on a different private EC2 host?

    Show answer

    Loopback names the application's own network environment. Use the other service's authorized private address or endpoint and appropriate credentials and policy.

Independent practice tasks

  1. Choose a second item for the supply desk. Describe the difference between an approved code with zero quantity, an invalid code and a dependency failure.

  2. Draw a front-server route for the static notice and another for the current-stock API. Label each response producer, transport and check.

  3. Run the prototype in its scratch scope and record the two query results, unchanged snapshot and deliberate dependency failure. Describe what would need new verification in a MySQL deployment.

Revision cards

Prepared bytes
The static server can send a previously generated file without calculating its data at request time.
Dynamic response
Application code uses request inputs or current dependencies to create the response.
Logical tier
A distinct responsibility such as routing, running business rules or managing stored data.
Upstream interface
The approved address or socket and protocol that the front server and runtime agree to use.
Parameterized query
The application sends data values separately from the SQL statement structure.
Dependency test
Exercise a concrete action such as reading a known row, independently of a simple readiness or static-page check.

Official sources