Reading notes from 2017; technical explanations revised November 17, 2026. Architecture and scale observations refer to the source period.
Put a service boundary around Spark sessions
Livy exposes a REST interface for Spark sessions and submitted work. That can centralize authentication, admission, logs, and session lifecycle. Cached objects are associated with the Spark application/session that owns them; an HTTP interface does not create one universal cache across all jobs.
Complete Python 3 session lifecycle
This example uses requests==2.32.3 and a Livy 0.8 REST endpoint. Set LIVY_URL to an authorized test server; configure authentication for that server rather than exposing Livy anonymously. The server needs a working PySpark installation.
import os
import time
import requests
base = os.environ["LIVY_URL"].rstrip("/")
http = requests.Session()
session_url = None
def wait_for(url, wanted, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
response = http.get(url, timeout=15)
response.raise_for_status()
value = response.json()
if value["state"] in wanted:
return value
if value["state"] in {"error", "dead", "killed"}:
raise RuntimeError(value)
time.sleep(1)
raise TimeoutError(url)
try:
response = http.post(base + "/sessions", json={"kind": "pyspark"}, timeout=30)
response.raise_for_status()
session_url = base + "/sessions/" + str(response.json()["id"])
wait_for(session_url, {"idle"})
response = http.post(session_url + "/statements",
json={"code": "print(sum(range(10)))"}, timeout=30)
response.raise_for_status()
statement_url = session_url + "/statements/" + str(response.json()["id"])
result = wait_for(statement_url, {"available"})["output"]
if result["status"] != "ok":
raise RuntimeError(result)
print(result["data"]["text/plain"])
finally:
if session_url:
http.delete(session_url, timeout=15).raise_for_status()
http.close()
The statement should print 45. Polling session readiness and statement completion are different steps. A production client also needs cancellation, ownership checks, session expiry, and per-user quotas. The cleanup runs even after a failed statement.
Conceptual illustration; labels describe responsibilities, not a deployment specification.

Livy sits between REST clients and Spark execution in the PayPal source diagram. Historical source figure; attribution and context are in References.