Skip to content
ImagineWorld

Load Balancing and HTTP

node_idnode-book_the-software-developer-s-guide-to-linux_chapter-15-load-balancing-and-http
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num15
chapter_titleLoad Balancing and HTTP
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

We’re going to take a slightly different approach with this chapter, so buckle up. On the one hand, we’re going to review some background on the Hypertext Transfer Protocol (HTTP) and focus on some misconceptions that trip up many web developers in the real world.

On the other hand, we’re going to keep this practical and cover one of the most powerful standard HTTP tools that’s available on the command line, curl. Specifically, we’re going to teach you the basics of curl in the context of how you can use it to troubleshoot common web application issues.

We assume that if you’re a web developer, you already know your way around HTTP. So, while the goal of this chapter is not to teach you the absolute basics of this protocol, we are going to review some of those basics to get you up to speed if it’s been a while. If you are totally new to HTTP, there is lots of excellent documentation on the web that you can use. For what it’s worth, we highly recommend MDN by Mozilla as your source for this information.

Instead, we want to focus on the common misunderstandings and pitfalls around HTTP and how it’s used in the real world, which often catch people by surprise. These misunderstandings often come from the fact that as a developer, you write web applications in a very simple local environment but run them in complicated production setups that look quite different from the laptop you built and tested them on.

This difference between what an application interacts with when in development on a local machine, and the infrastructure around it after it has been deployed to a staging or production environment, is the source of much confusion and many subtle bugs.

In this chapter, we’ll cover the most important of these differences: you’ll learn about gateways, upstreams, and other concepts that intersect with the infrastructure layer around a modern website or web application. Then we’ll cover some of the most common mistakes people make with HTTP that cause hard-to-debug issues with headers, status codes, and more. We’ll look at some of the modern security features that have been added, such as Cross-Origin Resource Sharing (CORS), along with the history of HTTP and the versions you’re likely to come across. Finally, you’ll learn a bit about how load balancing is done: knowing the basics will prevent you from having an incorrect model of the client request path in your mind, which is a common source of design problems at the application/infrastructure boundary.

You’ll learn:

  • Some basic terminology that you’ll need to understand the more complex web infrastructure we discuss later in the chapter.
  • Common misunderstandings about HTTP statuses, which when fully understood, can help you write cleaner and more correct status-handling code.
  • HTTP headers, and some related problems you might see in your own web applications.
  • The different HTTP versions you might encounter in the wild.
  • How load balancing works, and why you need to understand it as a developer, even if you never plan on touching application infrastructure.
  • How to troubleshoot web issues relating to all of these topics from the command line with a tool called curl.

The only prerequisite knowledge for this chapter is a basic understanding of how HTTP requests work, and a basic idea of the developer tooling that exists for web applications (for example, you should know how to use your browser’s console and other dev tools to debug basic HTTP issues).

Let’s start with some basic terminology that will come in handy when we get to troubleshooting.

Later sections will use a few terms you may not be familiar with, so let’s quickly cover them here.

In today’s world, the gateway is usually an HTTP reverse proxy, a load balancer, and frequently a combination of both. This can be an HTTP server, such as nginx or Apache, a physical load balancer in the classical sense, or a cloud variant of this same idea. It can also be a content-delivery network (CDN). So, when you receive an HTTP status code mentioning an error related to the gateway, it’s one of these gateway devices or applications talking to you.

The upstream is the service that an application proxies to. In most situations, this will be the actual application or service, for example, an HTTP service you wrote. It is good to keep in mind that one can cascade or layer proxies, so there might be another intermediate proxy between the first proxy and the actual web application. For example, in many cloud infrastructures there is an ingress load balancer that handles and filters incoming traffic, behind which is an application load balancer that actually inspects the HTTP traffic and routes it to the right application server pool.

Now that we’ve covered a few bits of terminology that go beyond HTTP, you’re prepared for the later sections of this chapter. Let’s now take a closer look at a few commonly misunderstood parts of HTTP and start using the curl tool to practice common CLI troubleshooting commands.

When developing web applications and HTTP APIs, it can pay to be aware of a few details that many developers miss. Let’s look at a few of the key areas where knowing a bit extra can really pay off in terms of the reliability of the applications you create. The curl skills we cover in this chapter will also give you the ability to start troubleshooting something as vague as “the website is down” from the command line.

In the following sections, we will cover some of the common HTTP statuses you’ll encounter. We’ll also consider some important information and myths about these statuses that you should keep in mind.

A common way to check for errors is only checking for a 200 or the whole 2xx range of status codes to know whether a request was a success. There are some caveats to be aware of when doing this, though.

The 200 range (2xx, as in, every status code between 200 and 299) tends to indicate success and many APIs return 204 No Content to indicate that an operation was successful, especially when the API usually returns the resource that was created or modified, but in certain scenarios, like DELETEs or when it would be a waste of resources, it does not.

Checking to see whether a response status is inside the 2xx range might be enough for some applications, but it is important to understand that application logic like “if it’s not a 200, log an error” is wrong. Neither the 1xx range nor the 3xx range indicate an error, even though they aren’t 200s.

It’s somewhat rare to see the 1xx range without expecting it, since the most common situations involving 100s are things like switching to WebSockets, but that doesn’t make them errors. The 3xx status code is returned quite often to inform the client about redirections, and while it might indicate that some action is needed – perhaps updating a path for some content that has moved – it’s definitely not a failure on its own.

One status code in the 3xx range that tends to be seen a lot more often in production than in development is 304 Not Modified. This can be easily overlooked at development time and might also appear due to infrastructure changes or library updates that improve or introduce new caching behaviors. This status code is used when the client, such as a browser or an HTTP library, sends the request with an If-Not-Modified header, especially to take advantage of caching.

For these reasons, it usually makes sense to only consider status codes starting with 400 to be any kind of potential error, instead of considering only 2xx status codes to be a success. This still lends itself to neat logic inside your application: checking if a status code is greater than or equal to 400 is just as concise as checking to see if it’s in the 2xx range.

Something important to keep in mind is that the Not Found status code can mean different things depending on the application. 404 can be returned by (file) servers and gateways, but also by the application. It can imply that a route does not exist, but also that a specific resource (for example, a post or comment) does not exist for some reason (for example, if, it was deleted).

This is why 404 is often part of the normal response set returned by a healthy application that’s working as designed. In some situations, a client might even depend on this behavior, for example to verify that something doesn’t exist – before creating a certain resource or when indicating to a user whether a certain resource or resource name is already taken.

In other words, the 404 status code alone (without more context about the application and the request) isn’t enough to indicate a problem. As you just saw, it may even indicate a success on multiple levels and layers. This is sometimes avoided by not using it in the application layer and signaling any “Not Found” situations differently, for example by still returning a status code of 200. What the right way is depends on both the application and what a team or standard agrees on, and which architectural style is used in your application.

This status code means that the gateway didn’t understand what the upstream returned; in other words, the response to the request that the gateway forwarded wasn’t a complete and valid HTTP response. This typically indicates a problem with the upstream service.

A 503 usually means that the upstream service isn’t reachable on the port that the gateway is configured to try. Practically, this means that the web application might have crashed, or that it’s not listening for HTTP requests, or that it’s listening on the wrong port, or that it’s blocked by a firewall rule or a broken routing rule, or a myriad of other reasons.

When a gateway creates a connection to an upstream, this connection times out at some point. This is important because hanging processes consume resources on both ends; on the gateway and the service. Usually, such timeouts only occur if this is unexpected and there are no bytes being written or read.

If the upstream service has a long-running request caused by waiting for computation or something similar, one option is to increase the time a request can take until this timeout occurs. However, it is usually advisable to take a different approach. For example, making that endpoint asynchronous or starting to write bytes earlier (such as by streaming data) can help.

The reason for this is that until there is a timeout, resources are used up and the requesting side doesn’t know whether the application will ever return a response. So, if the web service malfunctions, neither the gateway nor the client will know about it. This might also cause the gateway to think that the malfunctioning service is still up and running, instead of quickly detecting the problem and failing over to another instance of the service.

Introduction to curl: checking HTTP response status

Section titled “Introduction to curl: checking HTTP response status”

If you learn only one command-line tool to help you troubleshoot HTTP, you would do well to learn curl. As we continue to talk about areas of HTTP that are useful to understand in more depth, we’ll add sections like this to show you practical curl commands you can use while troubleshooting common issues related to the aspects of HTTP we just covered.

The simplest curl invocation is something like this:

curl https://tutorialinux.com/

This is just like pasting the URL into the browser – except it cuts out the browser and directly returns the web server’s response on the command line. Not the most exciting way to browse the web, to be sure. Let’s do something that’s a bit more useful for your next troubleshooting script: checking the status of an HTTP response!

Curl can easily be used to check whether a web server is up and responding to requests:

curl -IsS https://tutorialinux.com/ | head -n 1
HTTP/2 200

Based on this output, we know that the web server is up and the / route is responding with a 200 OK status. You also see the HTTP version here (HTTP/2), which we’ll discuss later. Specifically, this command issues a HEAD request (-I or --head), muting curl’s progress and error messages (-s or --silent).

You’ll still see error messages when something is wrong, though, thanks to the -S (or --show-error) option:

curl -IsS https://tutoriajsdkfksjdhfkjshdflinux.com/ | head -n 1
curl: (6) Could not resolve host: tutoriajsdkfksjdhfkjshdflinux.com

Finally, we’re chopping off most of the headers and only looking for the status code, which is the first line (| head -n 1).

However, you’ll often want to see the headers when troubleshooting. Let’s look at a few header-related HTTP gotchas and then try using curl to inspect headers.

The headers in HTTP are case-insensitive. Some software relies on this fact, and as a result certain gateways might modify and “normalize” these headers. Fortunately, it is rare for developers to directly interact with raw header values when writing a web application. Instead, they use web libraries, which abstract most of this complexity away and take care of these kinds of details. However, you should still make sure this is the case and normalize them, for example by lower-casing headers that your web application sets. This can also prevent situations where response headers are accidentally added multiple times with different letter casings.

When you create custom HTTP headers for an application, be aware of the prefix you decide to use. It used to be common to prefix custom headers with X-, for example X-My-Header. This practice is now considered bad (see RFC 6648, which deprecates it). Instead, it makes sense to create a custom prefix, such as the name of the project, product, or company, or an abbreviation of it. This prevents situations where that header will be reused by other developers who mistake it for an official part of the HTTP standard.

The -I option we introduced in the previous curl example is useful for viewing the response headers, which can help reveal caching problems, content-type mismatches, and other issues. Let’s see what the tutorialinux server has to say in its headers:

curl -I https://tutorialinux.com/
HTTP/2 200
server: nginx/1.24.0
date: Sat, 21 Oct 2023 16:37:12 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding
x-powered-by: PHP/8.2.11
link: <https://tutorialinux.com/wp-json/>; rel="https://api.w.org/"
strict-transport-security: max-age=31536000; includeSubdomains; preload

There’s nothing wrong with the server at the moment, but these headers already give me a few ideas of how to improve my nginx configuration: leaking software names and version numbers is usually a bad idea from a security perspective, and no one receiving HTML or JSON from this server needs to know that the backend is using PHP.

To explain some of the newer HTTP features you’ll see used, we’ll give you a brief history of the protocol. HTTP has been around for a while and has changed a lot, especially in recent years as web applications have come into vogue. The main concepts and primitives have largely remained the same since HTTP’s inception, however, some tricks, optimizations, and behaviors have changed. Being aware of the protocol version can help with debugging or preventing issues and reduce unnecessary or counter-productive optimizations and workarounds.

You’re unlikely to come across this version of HTTP anymore. It is the most minimal HTTP one can imagine. HTTP/0.9 allows for sending a GET request to a server and receiving what we now call the body of an HTTP request. No headers were sent or returned, not even a version header or a status code.

HTTP/1.0 and especially HTTP/1.1 came a lot closer to what people think of when they think of HTTP today. While HTTP/1.0 added a version number and headers, HTTP/1.1 paved the way for methods and a substantial number of extensions, usually in the form of headers.

HTTP/1.1 also added (and defaults to) pipelining. This means that multiple requests could be sent using the same TCP connection. Another widely used addition is the Host header, which allows for the same server or IP to use multiple hostnames.

For example, a web server could now be configured to respond with requests for http://example.org/, http://www.example.org/, http://forum.example.org/, and http://blog.example.org/ without requiring a separate IP address for each of them.

HTTP/1.1 also enabled many extensions: caching, compression, various authentication schemes, content negotiation, and even things like WebSockets. All of these are widely used in today’s web.

There are many articles extolling the virtues of HTTP/2. It is a huge and controversial step in a new direction for HTTP. While HTTP/1.1 was a text-based protocol that allowed anyone to create complete and valid requests in a terminal or text editor, HTTP/2 is a binary protocol that also handles streams, which are a mechanism to create a lightweight variant of a TCP connection.

The binary format and header compression mean that dedicated tools are now required to talk to an HTTP server (or client). The overall concepts, however, have remained the same as in earlier versions of HTTP, so as a web developer you’ll only notice the differences in specific situations.

While HTTP/2 also adds a lot of entirely new features, many of them are rarely used in user-facing web applications and might not even be implemented by browsers.

While this isn’t technically part of the official standard, HTTP/2 in the browser is typically limited to HTTPS.

In most situations, web applications will benefit from enhancements such as using a single TCP connection with multiple streams, especially when many requests, such as those for static files and AJAX, are made in parallel. This can render some optimizations, like sprite sheets or combining many files into a single one, unnecessary. When some of these optimizations lead to redundant data being transferred, they might even be counterproductive.

Some applications designed for HTTP/1.1 might require changes when switching to HTTP/2, because things like keeping connections alive might have unpredictable side-effects. For this and other reasons, it’s a good idea to test web applications before converting them to HTTP/2. There are even instances where people have found that switching their applications to HTTP/2 increases page load times or increases resource use.

This means that real life tests and monitoring to compare the differences between HTTP protocols are a good idea. Since many of the benefits of HTTP/2 target real-life usage by web browsers, a simple command-line load test might not give the same results as real users accessing the web application. A typical mistake, for example, is not taking HTTP/1.1’s pipelining feature into consideration.

However, for most real-life websites, HTTP/2 will bring benefits. For internal HTTP APIs on microservices, many companies are choosing to keep using HTTP/1.1 or gRPC.

HTTP/3 builds on the developments of HTTP/2 and moves its concepts to a UDP-based transport protocol called QUIC (instead of TCP, which all other HTTP versions use).

Like the previous version of HTTP, HTTP/3 uses streams as a lightweight alternative to establishing a new TCP connection. Unlike HTTP/2 this isn’t done by initiating streams inside an existing TCP connection, but rather by using QUIC, which is a protocol designed to allow for such streams.

QUIC has some advantages over TCP for common HTTP use cases. For example, because it’s UDP-based – UDP is the User Datagram Protocol, a more bare-bones but faster alternative to TCP – QUIC prevents situations where the whole connection can stall because a single packet hasn’t arrived (yet), even if that packet is destined for a different stream. QUIC is also optimized for quickly establishing that initial connection, including initiating TLS to secure the connection between the client and server. QUIC itself was created with extensibility and support for future versions in mind, and shortly after its standardization many such extensions were already on their way to being standardized.

Since HTTP/3 is based on UDP and designed to avoid protocol ossification, many traditional forms of intermediate nodes and gateways become obsolete.

Note

Protocol ossification is what happens when intermediate nodes (or anything that interacts with a protocol) require a protocol to keep a certain form, thereby making it hard to continue developing and changing that protocol (for example by adding extensions).

Let’s look at how these basic HTTP concepts fit into the larger infrastructure that most of your web applications will be running in. In an architecture like this, it’s rarely just a single web server and a client (like your web browser or curl): there are usually several layers of HTTP communication happening, and simple problems can compound and become hard to troubleshoot.

As usual, we’ll give you the most important concepts you need to understand, followed by a few practical tips on troubleshooting more complex web infrastructures using curl on the command line.

Load balancing is a way to spread the load destined for a service across many instances of that service. While this is certainly not limited to HTTP and web services, HTTP is one of the most common contexts in which load balancing is used today.

It’s important for you to understand how web application load balancing works, because it affects how bugs and problems show up in production. For example, in your local development environment, you are usually dealing with a single client (your browser or another API consumer) and a single server (the web application or service you’re working on). In the real world, there are often multiple layers of servers between your client and the application, each speaking and relaying your HTTP traffic and possibly introducing its own problems or bugs into the flow.

The material in this section will give you a high-level understanding of the moving parts that become part of the application as a whole, even though they’re not part of the application code you write.

HTTP load balancing is usually achieved by putting a layer of infrastructure in front of the application to proxy HTTP requests; usually one of the following:

  1. Gateway service, such as an HTTP server supporting it (such as nginx or Apache)
  2. Dedicated service (such as HAProxy or relayd)
  3. Cloud service (GCP’s Load Balancer, AWS’s ELB or ALB, and so on)
  4. Hardware load balancer

Sometimes, engineers choose to use a custom service or a DNS-based solution, especially in the context of regional load balancing which is often used as an additional layer in front of one of the other methods mentioned above. Container orchestrators and dedicated service discovery mechanisms also usually provide yet another mechanism for load balancing.

Introducing load balancers into the mix pulls in a few other concepts to understand – specifically around how these load balancers actually map requests coming from a client to a server running an instance of the web application that you lovingly crafted.

Session and cookie management becomes complex, because long-running sessions are no longer guaranteed to hit the same server every time. One server in your application pool going down becomes an issue – will your users’ experience be interrupted, or will they lose data? Will you, as an engineer troubleshooting your own web application, be unable to replicate an issue because it’s only happening on a single server out of tens or hundreds?

Understanding how modern load balancing works is essential to avoid application design flaws or troubleshooting woes like this, and the next few sections will equip you with a basic mental model that you can use to avoid them.

Sticky sessions, cookies, and deterministic hashing

Section titled “Sticky sessions, cookies, and deterministic hashing”

When setting up load balancing for HTTP services, one of the first questions to ask is whether a service requires sticky sessions. Sticky sessions are a mechanism for tying a client to a specific application server for the duration of the session; they’re often required for applications that keep session state on the application server itself.

This is one of the reasons why it’s best practice to design “stateless” applications, which write state to a shared data layer – in these applications, it doesn’t matter if a client’s first request is handled by a different server than that client’s second request. Thankfully in today’s world, especially when relying on a cloud-based infrastructure, sticky sessions are usually not required. However, this is something to keep in mind, especially when troubleshooting issues that mysteriously only crop up in load-balanced production environments.

While there are many ways to create sticky sessions in HTTP, the most common way is through cookies. This can either be via application cookies (such as session cookies) that the load balancer is aware of, or via dedicated cookies that the load balancer manages on its own.

Implementing sticky sessions by storing additional state on the load balancer is fraught with its own problems, though. If a load balancer must keep an internal mapping of IP addresses to application servers, what happens if that load balancer goes down and is replaced, losing that state? You can see that we’ve simply moved the state problem from the application server to the load balancer, and are hoping that nothing bad happens there. However, as the adage says, hope is not a viable strategy.

One clever way to achieve sticky sessions without dealing with the problem of needing to store state on the load balancer is to load balance using an IP hash. To achieve this, a hash of the client’s IP is created and used to map request IPs to instances of a service. As long as the IP of the client stays the same, the session will be “sticky” to that particular application instance.

Now, one or many load balancers will deterministically match IPs to application servers, without needing to communicate or share state. Servers can come and go as they please, and each new server will make the same matching decisions as all other servers, since they’re all using the same hashing algorithm and will always match a given IP to the same application server.

If sticky sessions aren’t required, the most common mechanism for balancing load is round-robin. This means that every new connection or request is routed to the next instance. In mathematical terms this means that the instance is chosen by request_count % instance_count (% being modulo).

You now have a high-level overview of how HTTP load balancing works in the real world. Of course, there are many other mechanisms that can be chosen, such as spreading the load based on resource usage, but you should be careful to really understand the effects of added complexity – many “clever” load-balancing algorithms are not without major pitfalls.

For example, resource-utilization-based load balancers can encounter problems handling short spikes in load, which can cause underutilization of one instance and over-utilization of another, because the real-life workload the service deals is spiky and the load measurements come at the wrong time and don’t even out these spikes.

Adding another layer of complexity to even out such spikes might cause other issues such as having many of these spikes stack on top of each other. If you find yourself leaving the well-trodden path of more established load-balancing mechanisms, make sure your team is putting enough technical consideration into the architecture and the context of the actual application and its usage.

While a primary goal of load balancing might be to ensure quick responses, a load balancer will typically keep track of which services are reachable. It might use health checking to verify that the servers it sends requests to are fully functional. This means that load balancing is also a way to achieve high availability and often also an integral part of a zero-downtime architecture where a service can be replaced (for example, when a new version is deployed) without clients noticing.

This can be achieved by allowing some form of graceful shutdown of instances, where connections to clients aren’t simply dropped, but connections will remain active until they are fully processed, while new connections are only routed to updated instances. When the last session ends the outdated instance can be fully shut down.

Health checks allow a load balancer to determine whether a service is fully operational. The most basic check, of course, is whether a connection can be established. However in microservice architectures, an external dependency (like another service) not being reachable can prevent a service from properly responding to requests. This can also be indicated via a dedicated status endpoint.

Many application and infrastructure teams agree on a route like /healthcheck, whose status code indicates whether requests should be routed to the service. In some more complex environments, such a route might even indicate which kinds of requests can be routed to the instance.

When skilled application developers and platform/SRE teams get together, healthcheck routes can even be built to signal situations that require action from the infrastructure, such as the instance being critically unhealthy and needing to be replaced. If such routes are well designed, they typically also respond with additional context and information on the problem to ease debugging production issues.

As the infrastructure that supports a web application grows larger and more complex, the number of things that can go wrong increases exponentially, and is highly dependent on the specific architecture and application. One class of problem that becomes more likely the more layers of proxying and routing a web infrastructure has is redirect loops and general redirection errors.

Thankfully, this is something that a command-line tool like curl is perfectly positioned to troubleshoot.

As we just mentioned, redirects can be a common symptom of bugs, problems, and more generally unexpected behavior in a web application and its surrounding infrastructure. Use curl’s -L (or --location) option to follow them:

curl -IL http://www.tutorialinux.com/
HTTP/1.1 301 Moved Permanently
Server: nginx/1.24.0
Date: Sun, 22 Oct 2023 22:58:02 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: https://tutorialinux.com/
HTTP/2 200
server: nginx/1.24.0
date: Sun, 22 Oct 2023 22:58:02 GMT
content-type: text/html; charset=UTF-8
vary: Accept-Encoding
x-powered-by: PHP/8.2.11
link: <https://tutorialinux.com/wp-json/>; rel="https://api.w.org/"
strict-transport-security: max-age=31536000; includeSubdomains; preload

You’ll see that the server replies with a 301 (Moved Permanently) and the correct location, https://tutorialinux.com/. curl follows the redirect and makes a request to that new location, where it gets a 200 (OK) status.

This redirect is working as expected, but you can use this curl command to do things like identify redirect loops in an application or troubleshoot caching and routing issues in multi-layer load balancer setups.

Sometimes, though, you’ll need to go deeper and send data to a web application to troubleshoot it. curl can help there, too!

Having a quick curl command loaded up in your brain for API testing comes in handy more than you’d think. Especially when dealing with JSON APIs that accept POST data, it’s common to want to send some test data to an endpoint to make sure the backend is returning what you expect:

curl --header "Content-Type: application/json" \
--request POST \
--data '{"some":"JSON","goes":"here"}' \
http://localhost:4000/api/v1/endpoint

This command uses a few flags that you’ll want to remember. First, the --header (-H) argument lets you specify a header string to set (you can supply multiple headers by simply repeating this argument). Next, the --request (or -X) flag lets you specify the HTTP request type (by default, curl performs GET requests, but using this flag lets you change that). And when you’re POSTing or PATCHing some data, as in this case, you’ll want the --data (or -d) argument, which lets you send data.

In the case of --data, remember that bash escape characters play a role here, so for complex data you’ll probably find it easier to use the --data option, like this:

curl -X POST --data "@my/data/file" https://localhost/api/v1/endpoint

Remember to prepend the @ character to your filepath. If you’re sending complex data, read up on --data-raw, --data-binary, and --data-urlencode as well. You may need to send extra headers as well, depending on what your web application expects.

You’ve now seen how to get more interactive with the web applications you’re troubleshooting, using curl to send them custom data. But there’s one last curl trick we want to show you: TLS (short for Transport Layer Security, the way we encrypt modern web traffic in HTTPS) is not necessarily a “misunderstood” aspect of web applications, but it’s a common failure point that curl can help with.

Accepting and displaying bad TLS certificates with curl

Section titled “Accepting and displaying bad TLS certificates with curl”

curl gives us the --insecure option, which allows it to accept invalid TLS certificates from a server, and continue the request. This can come in handy when troubleshooting misconfigured servers:

curl --insecure -v https://www.tutorialinux.org/

The --insecure (-k) option will make curl behave as if the TLS certificate is valid, even if it isn’t. Obviously, this is a security risk and should only be used for troubleshooting, but it can make curl continue in cases where TLS certificate validation would fail and curl would normally abort the request.

Let’s take a quick look at one last piece of HTTP that’s worth learning a bit about if you have anything to do with building or troubleshooting web applications: CORS.

CORS stands for Cross-Origin Resource Sharing. That is a fancy word for saying resources, such as images, videos, HTML, JavaScript, or even Asynchronous Javascript and XML (AJAX) responses will be coming from a different hostname. To prevent situations where resources are loaded from a third party, the browser first asks that third party whether it is allowed to do so. This is called a pre-flight request.

A pre-flight request is an OPTIONS request that expects a response containing HTTP headers informing whether the request is allowed or not. Such a response typically has a 204 (No Content) status code and only contains the headers. If no such headers are found or the headers do not indicate that such a request is allowed, no subsequent request of the resource will be triggered.

Here is an example of what such an exchange might look like.

A browser opening https://www.example.org/ asks whether it is okay to POST to /api/test on api.example.org:

OPTIONS /api/test
Origin: https://www.example.org
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header, Content-Type

An accepting response would look like this:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://www.example.org
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-Custom-Header, Content-Type
Access-Control-Allow-Max-Age: 3600

Since this indicates that the request is allowed, the browser can subsequently send the original request, which is now authorized:

POST /api/test
Origin: https://www.example.org
Content-Type: application/json
X-Custom-Header: foobarbaz

In the case of a request that’s not allowed, there is no response with an error status that signals a rejection per se – just a lack of the expected Access-Control-Allow-Origin header. In this case, the client sees that the request is not authorized and logs an error.

You can see errors like this as they happen in your browser’s developer console. They’ll look something like this:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://not-allowed. (Reason: something).

This is just a quick introduction to CORS, because it’s a topic that’s important for web developers to understand. While it’s not specific to the command line, it’s not out of the ordinary for a developer to have to understand these concepts and check their web client for these kinds of error logs. For a deeper treatment of this material, we recommend MDN’s article on the subject, which you can find at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.

In this chapter, you learned what you need to know to avoid some of the common misunderstandings, bugs, and frustrating design flaws that we see when web applications leave a developer’s laptop and start to interact with the real world through complex infrastructure. You learned about some of the infrastructure that mediates access to your applications, like gateways and upstreams.

You also saw some of the most common mistakes that we see developers make with HTTP, and you’ll be able to use that knowledge to avoid hard-to-debug issues with headers, incorrect or vague status codes, and more. You learned about Cross-Origin Resource Sharing (CORS) and how HTTP has evolved into its current form.

Maybe most importantly, you saw how you can level up your game as a developer by learning a command-line tool like curl and combining it with your theoretical knowledge of HTTP.

What you learned in this chapter makes it possible for you to quickly and accurately troubleshoot web application issues, whether it’s identifying a redirect loop on a broken WordPress site, pinpointing a subtle caching issue by inspecting the headers returned by a Ruby-on-Rails application, or replicating a production bug (and verifying a fix) at four in the morning by POSTing specific JSON data to a development server.