python
30 lines · 7 steps
Building a resilient requests Session
A reusable HTTP session with automatic retries and backoff keeps flaky API calls from failing on the first hiccup.
Explained by
highlit
1import requests
2from requests.adapters import HTTPAdapter
3from urllib3.util.retry import Retry
4
5
6def build_session() -> requests.Session:
7 session = requests.Session()
8 retries = Retry(
9 total=4,
10 backoff_factor=0.5,
11 status_forcelist=(429, 500, 502, 503, 504),
12 allowed_methods=frozenset({"POST", "GET"}),
13 raise_on_status=False,
14 )
15 adapter = HTTPAdapter(max_retries=retries)
16 session.mount("https://", adapter)
17 session.mount("http://", adapter)
18 session.headers.update({"User-Agent": "billing-sync/1.0"})
19 return session
20
21
22def submit_invoice(session: requests.Session, invoice: dict, token: str) -> dict:
23 response = session.post(
24 "https://api.acme.example/v2/invoices",
25 json=invoice,
26 headers={"Authorization": f"Bearer {token}"},
27 timeout=(3.05, 27),
28 )
29 response.raise_for_status()
30 return response.json()
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Configuring retries at the adapter level means every request through the session inherits the same resilience policy.
- 2Exponential backoff with a status_forcelist retries only transient failures instead of blindly hammering the server.
- 3Always pair requests with explicit connect and read timeouts so a hung server can't stall your process indefinitely.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
typescript
import { Injectable, Scope, Inject, NotFoundException } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express'; import { DataSource } from 'typeorm';
Per-tenant database connections in NestJS
multi-tenancy
connection-pooling
dependency-injection
Advanced
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-resilient-requests-session-explained-python-636b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.