Skip to content
Solar Account.
Education & Software

Apache Livy for Data Engineers: Architecture, Integration, and Production Deployment

Apache Livy is an open-source REST service that enables remote, secure interaction with an Apache Spark cluster over HTTP. For data engineers, Livy abstracts complex cluster connection protocols, allowing external orchestrators, custom applications, and intera...

Apache Livy for Data Engineers: Architecture, Integration, and Production Deployment

Apache Livy is an open-source REST service that enables remote, secure interaction with an Apache Spark cluster over HTTP. For data engineers, Livy abstracts complex cluster connection protocols, allowing external orchestrators, custom applications, and interactive notebooks to submit batch jobs or run code snippets in Python, Scala, and R without local Spark installations or direct SSH access to cluster nodes.

Contents

Core Architecture and How Apache Livy Works

Apache Livy functions as a proxy layer situated between client applications and underlying Apache Spark clusters managed by resource managers such as Hadoop YARN, Apache Mesos, or Kubernetes. In traditional Spark workflows, submitting a job or initializing a driver node requires client machines to host the full Spark distribution, maintain network line-of-sight to cluster ports, and manage local environment dependencies. Livy eliminates these client-side requirements by exposing a stateless, stateless-friendly REST API.

The architecture of Apache Livy revolves around the central Livy Server daemon. When a client application sends an HTTP request to the Livy Server, the server parses the payload, validates security credentials, and interfaces with the cluster resource manager to launch a Spark application on behalf of the user. Depending on the request type, Livy creates either a persistent long-running Spark context or a short-lived batch application.

  1. Client / UI / Orchestrator

    • Sends REST / HTTP (JSON) requests to Livy Server
  2. Livy Server

    • Triggers YARN / K8s Submit to Spark Driver
  3. Spark Driver (Driver Context)

    • Manages Spark Executors:

      • Spark Execut. 1
      • Spark Execut. 2

(Conceptual model of Livy REST translation to remote Spark drivers)

【Microsoft Fabric】Data Engineeringとは?Spark機能・料金を解説 | AI総合研究所

Behind the scenes, Livy maintains RPC (Remote Procedure Call) communication with the remote Spark driver. This architecture provides distinct structural advantages for data platform engineering:

  • Client Decoupling: Client applications require only standard HTTP libraries, eliminating heavy Spark dependencies from microservices, Web APIs, and orchestration containers.
  • Multi-Tenant Session Isolation: Livy handles credentials and user impersonation, launching isolated Spark contexts for different tenants while enforcing cluster resource quotas.
  • Context Sharing: Multiple statements can be sent sequentially to a single persistent remote context, avoiding the cold-start overhead of launching new JVMs for every query.
  • Fault Recovery: When configured with state store backends like ZooKeeper or HDFS, the Livy Server can restart without losing tracking metadata for active cluster applications.

Interactive Sessions vs. Batch Job Submissions

Data engineers interact with Apache Livy primarily through two core resource paradigms: interactive sessions and batch jobs. Understanding when and how to utilize each model is critical for designing efficient data pipelines and interactive analytical platforms.

Interactive Sessions

Interactive sessions allow remote clients to execute code snippets iteratively within a long-running Spark Context. When a client issues a POST request to the /sessions endpoint, Livy launches a remote Spark application. Once initialized, clients submit code fragments (statements) to the /sessions/{sessionId}/statements endpoint.

The remote driver evaluates the code, executes execution plans across worker nodes, and holds the result state in memory across multiple requests. This paradigm powers interactive notebook platforms, exploratory data analysis interfaces, and applications requiring immediate transactional feedback.

Key attributes of interactive sessions include:

  • State Retention: Variables, DataFrames, temporary views, and cached tables persist between statement executions within the same session.
  • Multi-Language Support: A single session endpoint can execute PySpark, Spark Scala, SparkR, and Spark SQL snippets.
  • Lifecycle Management: Sessions remain active until explicitly terminated via a DELETE request or until they hit an idle timeout threshold defined by cluster configuration policies.

Batch Job Submissions

Batch job submissions follow a asynchronous execution pattern ideal for scheduled data transformations and production ETL (Extract, Transform, Load) tasks. Clients issue a POST request to the /batches endpoint, providing parameters such as application JAR path, primary Python file, main class name, driver memory allocation, executor count, and runtime arguments.

Livy translates this payload into a cluster-level submission (spark-submit), tracks the application's unique ID, and immediately returns a JSON response containing execution metadata. Orchestrators poll the /batches/{batchId} endpoint to track execution status (e.g., starting, running, success, or dead) and retrieve log stdout/stderr outputs.

Key attributes of batch submissions include:

  • Ephemeral Footprint: The underlying Spark application terminates automatically once the main class or script finishes processing.
  • Resource Efficiency: Memory and CPU resources are fully released back to the cluster resource manager immediately upon job completion.
  • Immutable Configuration: Application parameters, classpaths, and environment variables are set once at creation and cannot be mutated during runtime.

Comparing Apache Livy with Modern Spark Submission Methods

Selecting the right submission mechanism depends on platform architecture, security constraints, and interactive requirements. The table below compares Apache Livy against direct job submission protocols and alternative interface abstractions.

Capability / Attribute Apache Livy Spark Connect Databricks Jobs API AWS EMR Steps API Direct spark-submit (SSH/Local)
Primary Protocol HTTP / REST API gRPC (HTTP/2) HTTP / REST API HTTP / AWS SDK Remote Shell / Native RPC
Client Requirement None (HTTP Client only) Lightweight Client Library Cloud SDK / HTTP Client AWS CLI / SDK Full Spark Binary & Java/Python Runtime
Session Model Interactive & Ephemeral Batch Interactive DataFrame API Ephemeral Batch & Triggered Notebooks Ephemeral Batch Ephemeral Batch or Native Shell
Multi-Tenancy Support High (User Impersonation via Kerberos/Proxy) High (Decoupled client/driver execution) Managed Workspace Multi-Tenancy IAM / Cluster Isolation Low (Shared Host or User Accounts)
Orchestrator Integration Excellent (Native Airflow/Prefect Operators) Native Code / Airflow Spark Submit Cloud Native Integrations Cloud Native Integrations Complex (Requires SSH key management or fat containers)
Interactive Code Execution Raw Code Snippets (Strings over JSON) Native DataFrame operations via gRPC AST Workspace Notebook Execution Limited Script Arguments Native REPL over Terminal
Network Security Model Single HTTP(S) Gateway Port Encrypted gRPC Port HTTPS API Endpoint HTTPS AWS Endpoint Wide Range of Cluster Ports & SSH Access

Enterprise Security, Authentication, and Access Control

Deploying Apache Livy in production environments requires rigorous security configurations, particularly when serving multi-tenant organizations handling sensitive data. Livy acts as an authentication bridge between external clients and enterprise Hadoop or Kubernetes clusters.

Authentication Mechanisms

Livy supports multiple authentication mechanisms to verify client identity before processing jobs:

  1. SPNEGO / Kerberos Authentication: In secured Hadoop environments, Livy uses SPNEGO to authenticate incoming HTTP requests against an enterprise Key Distribution Center (KDC). Clients pass Kerberos tickets in the HTTP Authorization header.
  2. HTTP Basic Authentication: Used primarily in containerized or cloud-native setups behind reverse proxies, validating user credentials against LDAP, Active Directory, or custom identity providers.
  3. Proxy User Impersonation: When configured with Hadoop impersonation rights, the Livy Server accepts requests from a service account (e.g., an Airflow runner) but executes the underlying Spark job under the end user's identity (e.g., proxyUser: "jdoe"). This ensures file system ACLs and HDFS permissions are accurately enforced at the storage layer.

Transport Security and Network Perimeter Control

To prevent unauthorized inspection of payloads containing code snippets or data frames, SSL/TLS encryption must be enabled on the Livy Server interface (livy.keystore and livy.keystore.password). Secure setups routinely deploy Livy behind an API Gateway or Apache Knox topology.

Apache Knox provides perimeter security by encapsulating authentication, routing, and audit logging into a single edge interface. This eliminates direct external access to Livy's port (default 8998) and shields internal cluster topologies from exposure.

Access Control Lists (ACLs)

Livy provides access control list mechanisms to regulate who can view, modify, or terminate active sessions and batch submissions:

  • View ACLs (livy.server.access-control.view-users): Restricts log viewing and status polling to session owners or designated administrators.
  • Modify ACLs (livy.server.access-control.modify-users): Controls who can kill running sessions, issue new code statements, or adjust runtime parameters.
  • Superuser Overrides: System administrators can be granted global permissions to monitor and manage all active jobs across the platform.

Integrating Livy into Data Pipelines and Orchestration Engines

Data engineers frequently integrate Livy with orchestration engines like Apache Airflow, Prefect, or Dagster to decouple workflow schedules from heavy cluster management tasks.

Airflow Integration Patterns

Apache Airflow provides dedicated provider packages for Apache Livy (apache-airflow-providers-apache-livy). Instead of running the traditional SparkSubmitOperator—which requires Airflow worker containers to host Spark binaries and cluster configuration files—engineers use the LivyOperator.

The workflow pattern operates as follows:

  1. Job Definition: Airflow constructs a JSON payload detailing the location of the compiled JAR or Python script stored in object storage (S3, GCS, ADLS) alongside job configurations.
  2. Submission: The LivyOperator issues an asynchronous POST request to the Livy REST API endpoint (http://livy-server:8998/batches).
  3. Polling and Deferral: Airflow records the batch ID returned by Livy. Using modern Airflow deferment mechanisms (Triggers), worker slots are released while the trigger periodically polls the Livy batch status endpoint (GET /batches/{id}).
  4. Log Capture and Termination: Upon state change, Airflow fetches the final execution logs and metrics via Livy APIs and marks the DAG task as successful or failed.

Custom REST Client Integration

For custom microservices or web platforms, integrating with Livy requires standard HTTP REST calls. Below is a conceptual walkthrough of an interactive session workflow:

  1. Create Interactive Session: Send POST request to /sessions with payload defining language (e.g., {"kind": "pyspark"}). Receive response containing session id: 12.
  2. Poll Session Readiness: Send GET request to /sessions/12. Wait until the state field changes from starting to idle.
  3. Submit Code Statement: Send POST request to /sessions/12/statements with payload specifying code: {"code": "df = spark.read.json('s3://bucket/data.json')\nprint(df.count())"}. Receive statement id: 0.
  4. Retrieve Results: Send GET request to /sessions/12/statements/0. Poll until state is available, then parse the returned execution output JSON payload.
  5. Close Session: Send DELETE request to /sessions/12 to free cluster resources.

Operational Pitfalls, Session Governance, and Troubleshooting

While Apache Livy simplifies remote cluster access, managing Livy in high-throughput enterprise environments presents operational challenges that require active governance.

1. Interactive Session Resource Leaks

A major operational issue in shared Livy environments occurs when clients open interactive sessions and abandon them without issuing explicit DELETE calls. Left unchecked, orphaned sessions hold YARN containers or Kubernetes pods open indefinitely, consuming cluster memory and CPU cores.

Mitigation Strategy: Configure strict server-side timeout policies in livy.conf:

  • livy.server.session.timeout = 1h: Automatically terminates interactive sessions that receive no new statement requests within the configured timeframe.
  • livy.server.session.max-creation = 100: Limits total concurrent active sessions on a single server instance to avoid resource exhaustion.

2. Single Point of Failure and High Availability Setup

By default, the Livy Server daemon is a single process. If the host machine crashes, tracking context for active jobs can be lost.

Mitigation Strategy: Enable High Availability (HA) and Recovery modes. Configure Livy to store state metadata in ZooKeeper (livy.server.recovery.mode = zookeeper) and back application states in HDFS or shared object storage (livy.server.recovery.state-store-url). If the active Livy instance fails, a standby daemon reads the state store, reconnects to existing YARN/K8s applications, and resumes REST API tracking seamlessly.

3. Out-Of-Memory (OOM) Errors in Livy Server

The Livy Server daemon process routes status metadata and large result payloads returned by interactive statements. If a client executes a statement that collects millions of records to the driver (e.g., df.collect()) and returns them via Livy's JSON interface, the Livy Server heap memory can saturate quickly, triggering Garbage Collection (GC) pauses or fatal OOM errors.

Mitigation Strategy: Enforce proper Spark application coding standards. Prohibit full dataset collections to the driver in interactive statements, relying instead on df.show(50) or localized sampling. Additionally, tune Livy Server JVM arguments in livy-env.sh to allocate sufficient heap space (e.g., -Xmx4g or -Xmx8g).

Modern Strategic Recommendations for Data Engineers

As data platforms evolve, platform architects must evaluate where Apache Livy fits alongside emerging industry alternatives.

When to Choose Apache Livy

  • Heterogeneous On-Premise Clusters: When operating legacy Hadoop/YARN clusters where direct SSH or client binary distribution to external tools creates network security vulnerabilities.
  • Centralized Gateway Architecture: When platform engineering teams require a centralized, auditable, Kerberos-authenticated REST proxy for multi-tenant submission.
  • Custom Internal Platforms: When building internal web consoles or custom data applications that require submitting ad-hoc jobs via basic HTTP standard libraries.

When to Consider Alternatives

  • Spark 3.4+ Ecosystems (Spark Connect): For organizations modernizing interactive client workflows on newer Spark versions, Spark Connect provides a robust alternative. Spark Connect decouples the client from the driver using a gRPC architecture, allowing full native DataFrame code completion, local debugging, and IDE integration without raw string sending over REST JSON.
  • Fully Managed Cloud Platforms: When operating exclusively within AWS (EMR), GCP (Dataproc), or Databricks, platform-native APIs (such as EMR Serverless APIs or Databricks Jobs API v2.1) offer deeper cloud integration, automated scaling, and identity management out of the box.

Frequently Asked Questions

What is the default port for Apache Livy and how is it secured?

Apache Livy defaults to port 8998. In production deployments, this port is secured by enabling SSL/TLS encryption (livy.keystore), configuring Kerberos SPNEGO authentication, and routing traffic through an edge gateway like Apache Knox to restrict network access.

How does Apache Livy handle dependencies like third-party Python packages or JAR files?

Dependencies can be specified in the JSON payload during batch or session creation. Users include file paths or remote URIs using configuration keys such as jars, pyFiles, files, or archives. Livy forwards these configurations to the underlying Spark submission mechanism, distributing assets to worker nodes across the cluster.

Can Apache Livy run on Kubernetes-backed Spark clusters?

Yes. Apache Livy can submit jobs to Kubernetes-managed Spark clusters. The Livy server communicates with the Kubernetes API server, dispatching Spark driver pods and leveraging native Kubernetes resource scheduling while maintaining its standard REST API layer for client interaction.

What is the main difference between Livy interactive sessions and Livy batch jobs?

Interactive sessions keep a remote Spark Context alive across multiple API calls, allowing incremental statement execution and state sharing within memory. Batch jobs launch an isolated, single-use Spark application that runs a pre-compiled JAR or script to completion and immediately terminates, freeing cluster resources.

How does Apache Livy compare to Spark Connect?

Apache Livy is a REST-based gateway that transmits code as raw text strings over JSON, making it ideal for legacy infrastructure and multi-language REST integrations. Spark Connect is a client-server architecture based on gRPC introduced in modern Spark versions, allowing clients to construct native Spark DataFrame code in local IDEs while sending execution trees directly to remote drivers.

Next Steps for Implementing Apache Livy

To successfully integrate Apache Livy into your production data infrastructure, consider the following implementation path:

  1. Assess Network Topology: Evaluate your network perimeter to determine if Livy should sit directly on an edge node or behind an enterprise gateway such as Apache Knox.
  2. Define Session Governance Policies: Establish strict idle timeout limits (livy.server.session.timeout) and user access controls prior to opening ports to internal data consumers.
  3. Deploy High-Availability State Stores: Configure ZooKeeper and HDFS state storage backends to prevent job tracking loss during host maintenance or container restarts.
  4. Standardize Orchestrator Hooks: Upgrade Airflow or Prefect pipelines to use lightweight HTTP-based Livy operators, removing heavy Spark binaries and configuration files from orchestration agent containers.

Written by

Hannah Brooks

Higher Education & Career Writer