Part 03 · The Language of the Web
Keep-Alive and Connection Reuse
Why opening a new connection per request is expensive, and how reuse saves the day.
⏱ 1 hours · Station 34 of 153
The payment API that was "slow"
Your checkout service calls a payment provider's API for every order. The provider promises responses in 20 ms, but your logs show every call taking 120 ms. You open a ticket. The provider replies: "Our server time is 18 ms. Are you reusing connections?"
You weren't. Your code created a new HTTP client for every call, so every call did DNS, a TCP handshake and a TLS handshake before sending a single byte, then threw the connection away. 100 ms of every request was setting up, not working.
Opening a connection is the most expensive thing an HTTP client does (Module 2: TCP costs a round trip, TLS another). Keep-alive means not closing the connection after a response, so the next request can go straight out. It's one of the cheapest, biggest performance wins in backend work, and also a source of strange bugs when idle connections quietly die.
The problem: setup costs more than the work
| Step | Cost | Paid on every new connection |
|---|---|---|
| DNS lookup | 0-50 ms (often cached) | sometimes |
| TCP handshake | 1 round trip | yes |
| TLS 1.3 handshake | 1 round trip + crypto CPU on both sides | yes |
| TCP slow start | first round trips carry little data | yes |
| The actual request and response | 1 round trip | that's the useful part |
With a 50 ms round trip, a new HTTPS connection costs about 100 ms before the request even leaves. A small API call takes 50 ms more. Two thirds of the time is overhead, and the server burns CPU on TLS handshakes it didn't need to do.
Think of a phone call
You need to ask your friend five questions.
- Without keep-alive: dial, wait for them to pick up, say hello, ask one question, hang up. Dial again for the second question. Five times.
- With keep-alive: dial once, say hello once, ask all five questions, then hang up when you're done (or after a minute of silence).
The questions take the same time either way. The dialling and the hellos are pure waste. And if you keep the line open for an hour without talking, the phone company may cut it without telling you; the next time you speak, nobody's there.
Where the analogy stops working. A phone line is one conversation; an HTTP client usually keeps a pool of open connections to each host, handing them out to requests and taking them back. And unlike a dropped call, a dead TCP connection isn't always noticed until you try to use it.
The building blocks
- HTTP/1.1 keeps connections open by default. After a response, the connection stays open for the next request unless either side sends
Connection: close. (In HTTP/1.0 it closed by default;Connection: keep-aliveasked otherwise.) - Framing makes it possible. The client knows where one response ends because of
Content-Lengthor chunked encoding (lesson 1), so it can send the next request on the same bytes stream. - Requests on one HTTP/1.1 connection take turns. One request, one response, next request. To run requests in parallel, clients open several connections (lesson 9); HTTP/2 multiplexes them on one.
- Connection pools. HTTP clients keep idle connections per host (scheme + host + port) and reuse them. Typical settings: maximum connections per host, maximum idle connections, and how long an idle connection is kept.
- Idle timeouts on both sides. Servers close connections that have been idle for a while (nginx's default keep-alive timeout is 75 s; many load balancers use 60 s). NAT devices and firewalls drop idle entries too (Module 2, lesson 12). Clients should close idle connections before the server does.
- Stale connections. If the server closes an idle connection at the same moment the client sends a request on it, the request fails (
connection reset,EOF). Good clients retry idempotent requests once on a fresh connection. - Server-side limits. Every open connection uses memory and a file descriptor. Servers limit concurrent connections and requests per connection, and may close long-lived connections to rebalance load.
- Reuse needs one long-lived client. In most languages, the pool lives inside the HTTP client object. Creating a new client per request creates a new pool, which means no reuse at all.
A service makes 1,000 calls per second to another service in the same data centre (RTT 0.5 ms) over HTTPS. Each call creates a new HTTP client. What happens when they switch to one shared client with a pool?
Behind the scenes: a pooled client, from first call to idle timeout
One host, one pool, many requests
Step 1/5 First request
The pool has no connection to api.pay.com yet. It dials: DNS, TCP handshake, TLS handshake. About 2 round trips before the request goes out.
- pool
- 0 idle
- round_trips
- 3
The picture to keep in your head
A connection is an expensive pipe: costly to build (handshakes), cheap to use (just a round trip per request).
- Build once, use many times: one long-lived client per service, with a pool per host.
- Return pipes after use: read the full response so the connection can go back to the pool.
- Retire idle pipes before the other side does: client idle timeout < server and NAT timeouts.
- Expect the occasional dead pipe: retry idempotent requests once on a fresh connection.
Try it: does this reuse connections?
Reused or rebuilt?
def handler(): client = HttpClient(); client.get(...)
Code from first principles
A tiny HTTP/1.1 server that counts how many connections it accepted and how many requests arrived on each. A client sends five requests twice: first with a new connection for each (sending Connection: close), then on one connection kept alive, using Content-Length to know where each response ends. The last line turns the connection counts into time on a 50 ms network.
package main
import (
"bufio"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
)
// The server counts how many TCP connections it accepted and how many requests came on each.
var (
mu sync.Mutex
perConn []int
)
func serve(ln net.Listener) {
for {
conn, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
perConn = append(perConn, 0)
id := len(perConn) - 1
mu.Unlock()
r := bufio.NewReader(conn)
for { // keep-alive: keep reading requests on this connection until the client closes it
head := ""
for !strings.HasSuffix(head, "\r\n\r\n") {
line, err := r.ReadString('\n')
if err != nil {
break
}
head += line
}
if head == "" {
break // the client closed the connection
}
mu.Lock()
perConn[id]++
mu.Unlock()
body := "ok"
fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s", len(body), body)
if strings.Contains(head, "Connection: close") {
break
}
}
conn.Close()
}
}
// readResponse reads one response, using Content-Length to know where it ends.
func readResponse(r *bufio.Reader) string {
length := 0
for {
line, _ := r.ReadString('\n')
if line == "\r\n" {
break
}
if v, ok := strings.CutPrefix(line, "Content-Length: "); ok {
length, _ = strconv.Atoi(strings.TrimSpace(v))
}
}
body := make([]byte, length)
io.ReadFull(r, body)
return string(body)
}
func report(label string, requests int) {
mu.Lock()
defer mu.Unlock()
fmt.Printf("%s: %d requests, server accepted %d connection(s), requests per connection %v\n", label, requests, len(perConn), perConn)
perConn = nil
}
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:8096")
go serve(ln)
const n = 5
// A: a new connection for every request.
for i := 0; i < n; i++ {
conn, _ := net.Dial("tcp", "127.0.0.1:8096")
fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n", i)
readResponse(bufio.NewReader(conn))
conn.Close()
}
report("new connection each time", n)
// B: one connection, reused for every request.
conn, _ := net.Dial("tcp", "127.0.0.1:8096")
r := bufio.NewReader(conn)
for i := 0; i < n; i++ {
fmt.Fprintf(conn, "GET /item/%d HTTP/1.1\r\nHost: localhost\r\n\r\n", i)
readResponse(r)
}
report("one kept-alive connection", n)
conn.Close()
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
rtt := 50
fmt.Printf("at %d ms RTT: new each time = %d x (2 + 1) round trips = %d ms, reused = (2 + %d) round trips = %d ms\n",
rtt, n, n*3*rtt, n, (2+n)*rtt)
}const net = require("node:net");
// The server counts how many TCP connections it accepted and how many requests came on each.
let perConn = [];
const server = net.createServer((conn) => {
perConn.push(0);
const id = perConn.length - 1;
let buf = "";
conn.on("data", (chunk) => {
buf += chunk;
let end;
// keep-alive: keep handling requests on this connection until the client closes it
while ((end = buf.indexOf("\r\n\r\n")) >= 0) {
const head = buf.slice(0, end + 4);
buf = buf.slice(end + 4);
perConn[id]++;
const body = "ok";
conn.write(`HTTP/1.1 200 OK\r\nContent-Length: ${body.length}\r\n\r\n${body}`);
if (head.includes("Connection: close")) conn.end();
}
});
});
// request sends one request on conn and resolves with the body, using Content-Length to know where it ends.
function request(conn, text) {
return new Promise((resolve) => {
let buf = "";
const onData = (chunk) => {
buf += chunk;
const end = buf.indexOf("\r\n\r\n");
if (end < 0) return;
const length = Number(/Content-Length: (\d+)/.exec(buf.slice(0, end))[1]);
if (buf.length < end + 4 + length) return;
conn.off("data", onData);
resolve(buf.slice(end + 4, end + 4 + length));
};
conn.on("data", onData);
conn.write(text);
});
}
const connect = () => new Promise((resolve) => { const c = net.connect(8096, "127.0.0.1", () => resolve(c)); });
function report(label, requests) {
console.log(`${label}: ${requests} requests, server accepted ${perConn.length} connection(s), requests per connection [${perConn.join(" ")}]`);
perConn = [];
}
server.listen(8096, "127.0.0.1", async () => {
const n = 5;
// A: a new connection for every request.
for (let i = 0; i < n; i++) {
const conn = await connect();
await request(conn, `GET /item/${i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n`);
conn.destroy();
}
report("new connection each time", n);
// B: one connection, reused for every request.
const conn = await connect();
for (let i = 0; i < n; i++) await request(conn, `GET /item/${i} HTTP/1.1\r\nHost: localhost\r\n\r\n`);
report("one kept-alive connection", n);
conn.destroy();
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
const rtt = 50;
console.log(`at ${rtt} ms RTT: new each time = ${n} x (2 + 1) round trips = ${n * 3 * rtt} ms, reused = (2 + ${n}) round trips = ${(2 + n) * rtt} ms`);
server.close();
});use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
// The server counts how many TCP connections it accepted and how many requests came on each.
fn serve(listener: TcpListener, per_conn: Arc<Mutex<Vec<u32>>>) {
for conn in listener.incoming() {
let mut conn = conn.unwrap();
let id = {
let mut p = per_conn.lock().unwrap();
p.push(0);
p.len() - 1
};
let mut reader = BufReader::new(conn.try_clone().unwrap());
loop {
// keep-alive: keep reading requests on this connection until the client closes it
let mut head = String::new();
while !head.ends_with("\r\n\r\n") {
let mut line = String::new();
if reader.read_line(&mut line).unwrap_or(0) == 0 {
break;
}
head += &line;
}
if head.is_empty() {
break; // the client closed the connection
}
per_conn.lock().unwrap()[id] += 1;
let body = "ok";
write!(conn, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}", body.len(), body).unwrap();
if head.contains("Connection: close") {
break;
}
}
}
}
// read_response reads one response, using Content-Length to know where it ends.
fn read_response(reader: &mut BufReader<TcpStream>) -> String {
let mut length = 0;
loop {
let mut line = String::new();
reader.read_line(&mut line).unwrap();
if line == "\r\n" {
break;
}
if let Some(v) = line.strip_prefix("Content-Length: ") {
length = v.trim().parse().unwrap();
}
}
let mut body = vec![0; length];
reader.read_exact(&mut body).unwrap();
String::from_utf8(body).unwrap()
}
fn report(per_conn: &Arc<Mutex<Vec<u32>>>, label: &str, requests: u32) {
let mut p = per_conn.lock().unwrap();
let counts: Vec<String> = p.iter().map(|c| c.to_string()).collect();
println!("{label}: {requests} requests, server accepted {} connection(s), requests per connection [{}]", p.len(), counts.join(" "));
p.clear();
}
fn main() {
let per_conn = Arc::new(Mutex::new(Vec::new()));
let listener = TcpListener::bind("127.0.0.1:8096").unwrap();
let shared = Arc::clone(&per_conn);
thread::spawn(move || serve(listener, shared));
let n = 5;
// A: a new connection for every request.
for i in 0..n {
let mut conn = TcpStream::connect("127.0.0.1:8096").unwrap();
write!(conn, "GET /item/{i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
read_response(&mut BufReader::new(conn));
}
report(&per_conn, "new connection each time", n);
// B: one connection, reused for every request.
let mut conn = TcpStream::connect("127.0.0.1:8096").unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
for i in 0..n {
write!(conn, "GET /item/{i} HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap();
read_response(&mut reader);
}
report(&per_conn, "one kept-alive connection", n);
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
let rtt = 50;
println!(
"at {rtt} ms RTT: new each time = {n} x (2 + 1) round trips = {} ms, reused = (2 + {n}) round trips = {} ms",
n * 3 * rtt,
(2 + n) * rtt
);
}import socket
import threading
# The server counts how many TCP connections it accepted and how many requests came on each.
lock = threading.Lock()
per_conn = []
def serve(listener):
while True:
conn, _ = listener.accept()
with lock:
per_conn.append(0)
cid = len(per_conn) - 1
reader = conn.makefile("rb")
while True: # keep-alive: keep reading requests on this connection until the client closes it
head = b""
while not head.endswith(b"\r\n\r\n"):
line = reader.readline()
if not line:
break
head += line
if not head:
break # the client closed the connection
with lock:
per_conn[cid] += 1
body = b"ok"
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % (len(body), body))
if b"Connection: close" in head:
break
conn.close()
def read_response(reader):
"""Read one response, using Content-Length to know where it ends."""
length = 0
while (line := reader.readline()) != b"\r\n":
if line.startswith(b"Content-Length: "):
length = int(line.split(b": ")[1])
return reader.read(length)
def report(label, requests):
global per_conn
with lock:
counts = " ".join(str(c) for c in per_conn)
print(f"{label}: {requests} requests, server accepted {len(per_conn)} connection(s), requests per connection [{counts}]")
per_conn = []
listener = socket.socket()
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind(("127.0.0.1", 8096))
listener.listen()
threading.Thread(target=serve, args=(listener,), daemon=True).start()
N = 5
# A: a new connection for every request.
for i in range(N):
conn = socket.create_connection(("127.0.0.1", 8096))
conn.sendall(f"GET /item/{i} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".encode())
read_response(conn.makefile("rb"))
conn.close()
report("new connection each time", N)
# B: one connection, reused for every request.
conn = socket.create_connection(("127.0.0.1", 8096))
reader = conn.makefile("rb")
for i in range(N):
conn.sendall(f"GET /item/{i} HTTP/1.1\r\nHost: localhost\r\n\r\n".encode())
read_response(reader)
report("one kept-alive connection", N)
conn.close()
# What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
rtt = 50
print(f"at {rtt} ms RTT: new each time = {N} x (2 + 1) round trips = {N * 3 * rtt} ms, reused = (2 + {N}) round trips = {(2 + N) * rtt} ms")import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class Main {
// The server counts how many TCP connections it accepted and how many requests came on each.
static final List<Integer> perConn = new ArrayList<>();
static void serve(ServerSocket listener) {
while (true) {
try (Socket conn = listener.accept()) {
int id;
synchronized (perConn) { perConn.add(0); id = perConn.size() - 1; }
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
OutputStream out = conn.getOutputStream();
while (true) { // keep-alive: keep reading requests on this connection until the client closes it
StringBuilder head = new StringBuilder();
String line;
while ((line = reader.readLine()) != null && !line.isEmpty()) head.append(line).append("\r\n");
if (line == null) break; // the client closed the connection
synchronized (perConn) { perConn.set(id, perConn.get(id) + 1); }
String body = "ok";
out.write(("HTTP/1.1 200 OK\r\nContent-Length: " + body.length() + "\r\n\r\n" + body).getBytes(StandardCharsets.UTF_8));
out.flush();
if (head.toString().contains("Connection: close")) break;
}
} catch (IOException e) {
return;
}
}
}
// readResponse reads one response, using Content-Length to know where it ends.
static String readResponse(InputStream in) throws IOException {
int length = 0;
while (true) {
StringBuilder line = new StringBuilder();
int c;
while ((c = in.read()) != '\n') line.append((char) c);
String l = line.toString().trim();
if (l.isEmpty()) break;
if (l.startsWith("Content-Length: ")) length = Integer.parseInt(l.substring(16));
}
return new String(in.readNBytes(length), StandardCharsets.UTF_8);
}
static void report(String label, int requests) {
synchronized (perConn) {
StringJoiner counts = new StringJoiner(" ");
for (int c : perConn) counts.add(String.valueOf(c));
System.out.println(label + ": " + requests + " requests, server accepted " + perConn.size() + " connection(s), requests per connection [" + counts + "]");
perConn.clear();
}
}
public static void main(String[] args) throws Exception {
ServerSocket listener = new ServerSocket(8096, 50, InetAddress.getByName("127.0.0.1"));
Thread server = new Thread(() -> serve(listener));
server.setDaemon(true);
server.start();
int n = 5;
// A: a new connection for every request.
for (int i = 0; i < n; i++) {
try (Socket conn = new Socket("127.0.0.1", 8096)) {
conn.getOutputStream().write(("GET /item/" + i + " HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.UTF_8));
readResponse(conn.getInputStream());
}
}
report("new connection each time", n);
// B: one connection, reused for every request.
try (Socket conn = new Socket("127.0.0.1", 8096)) {
InputStream in = new BufferedInputStream(conn.getInputStream());
for (int i = 0; i < n; i++) {
conn.getOutputStream().write(("GET /item/" + i + " HTTP/1.1\r\nHost: localhost\r\n\r\n").getBytes(StandardCharsets.UTF_8));
readResponse(in);
}
report("one kept-alive connection", n);
}
// What that means on a real network: a new HTTPS connection costs 2 round trips (TCP + TLS).
int rtt = 50;
System.out.printf("at %d ms RTT: new each time = %d x (2 + 1) round trips = %d ms, reused = (2 + %d) round trips = %d ms%n",
rtt, n, n * 3 * rtt, n, (2 + n) * rtt);
}
}Output (the same in all five languages):
new connection each time: 5 requests, server accepted 5 connection(s), requests per connection [1 1 1 1 1]
one kept-alive connection: 5 requests, server accepted 1 connection(s), requests per connection [5]
at 50 ms RTT: new each time = 5 x (2 + 1) round trips = 750 ms, reused = (2 + 5) round trips = 350 ms
Reading the output:
- New connection each time: 5 connections, 1 request each. Five TCP handshakes, and over the real internet five TLS handshakes too.
- Kept alive: 1 connection, 5 requests. The server's loop kept reading requests on the same connection until the client closed it.
- The client could reuse the connection only because of
Content-Length: it knew the response was exactly 2 bytes, so the next bytes would belong to the next response. - At 50 ms RTT, 750 ms vs 350 ms for the same five requests. The work is identical; only the setup changed.
And the same effect against a real server, measured with curl's num_connects (new connections opened for that transfer):
$ curl -s -o /dev/null -o /dev/null -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/ https://example.com/ https://example.com/
new connections 1, tls done at 0.099458s, total 0.107765s
new connections 0, tls done at 0.000000s, total 0.006453s
new connections 0, tls done at 0.000000s, total 0.008123s
$ for i in 1 2 3; do curl -s -o /dev/null -w "new connections %{num_connects}, tls done at %{time_appconnect}s, total %{time_total}s\n" https://example.com/; done
new connections 1, tls done at 0.023686s, total 0.031295s
new connections 1, tls done at 0.019792s, total 0.029106s
new connections 1, tls done at 0.021939s, total 0.031011s
- One curl process, three URLs: the first transfer opened a connection (DNS, TCP, TLS took 99 ms on this cold run), and the next two reused it: 0 new connections, about 6-8 ms each.
- Three separate curl processes: each one is a new client with an empty pool, so every request opened a new connection and took about 30 ms, four times longer than a reused one.
Real engineering
- One HTTP client per downstream service, created at startup. Go's
http.Client, Python'srequests.Sessionorhttpx.Client, Node'sundiciagent orkeepAlive: trueagents, Java'sHttpClient. Share it across requests and threads. - Always finish with the response. Read the body to the end (or close it). Unread bodies keep connections out of the pool.
- Tune the pool: max connections per host (enough for peak concurrency, not unlimited), idle connections kept, idle timeout below the server's and the load balancer's.
- Retry idempotent requests once on connection errors. Stale pooled connections are normal; a single retry on a fresh connection hides them. Don't auto-retry POST (lesson 4).
- Same idea for databases and Redis. Use a connection pool; size it for your concurrency and the database's limits (Postgres handles hundreds of connections, not thousands; poolers like PgBouncer help).
- Draining on deploy. When shutting a server down, stop accepting new requests and close keep-alive connections gracefully (send
Connection: closeon the last responses) so clients move to other servers without errors.
When it breaks
Pick a failure
read tcp: connection reset by peer (first request after idle)
Think before you read on
Keep-alive saves time by holding connections open. Why might a server deliberately close a perfectly healthy connection after, say, 1,000 requests or 10 minutes?
Reveal
To spread load. A load balancer picks a server when a connection is opened, not for every request. A client with one long-lived connection sends everything to the same server forever, so after a scale-up the new servers sit idle and the old ones stay hot. Closing connections occasionally forces clients to reconnect, and each reconnect gets balanced again. It also lets servers recover leaked memory, rotate TLS certificates and drain cleanly before deploys. The cost is one handshake per 1,000 requests, which is tiny.
Check yourself
1. What is HTTP keep-alive, and what does it save?
Answer
Keeping a TCP (and TLS) connection open after a response so the next request can reuse it. It saves the TCP and TLS handshakes (round trips and CPU) and TCP slow start on every request after the first.
2. How does a client know where one response ends on a kept-alive connection?
Answer
From the response framing: Content-Length says exactly how many body bytes to read, or chunked encoding marks the end. Without that, the only end marker would be closing the connection.
3. Why should a client's idle timeout be shorter than the server's?
Answer
So the client retires idle connections before the server closes them. Otherwise the client may send a request on a connection the server has just closed, and the request fails with a reset.
4. Why does creating a new HTTP client for every request defeat keep-alive?
Answer
The connection pool lives inside the client. A new client has an empty pool, so every request opens a new connection and the old one is thrown away.
Your challenge: build a tiny pool
Extend the code with a connection pool:
- Write
get()that returns an idle connection if one exists, otherwise dials a new one, andput(conn)that returns it to the pool. - Give each pooled connection a "last used" time and an idle timeout of 3 seconds (use a fake clock you advance by hand, as in earlier lessons).
get()must discard expired connections. - Send 3 requests, advance the clock by 5 seconds, then send 2 more.
Before you run it, predict how many connections the server will report accepting, and how many requests on each.
You've succeeded when the server reports 2 connections with [3 2] requests, your pool never hands out an expired connection, and making the idle timeout 10 seconds changes the report to 1 connection with [5].
The mental model
A connection is expensive to build (DNS, TCP, TLS, slow start) and cheap to use, so HTTP keeps it alive and clients keep a pool per host. Framing (Content-Length or chunked) is what lets several requests share one connection. Use one long-lived client, always finish reading responses, keep client idle timeouts below the server's and the network's, retry idempotent requests once on stale connections, and let servers recycle connections now and then so load stays balanced.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →