Part 10 · The Databricks platform · Chapter 36
Photon
Databricks' native vectorized engine: why it was built in C++, how its column batches and kernels adapt per batch, how its hash table probes, how it enters a Spark plan, and how it shares memory with Spark.
After this chapter you should be able to:
- Explain how Photon slots into a Spark physical plan, and predict where the transitions go.
- Describe position lists, kernel specialization and batch-level adaptivity, and their trade-offs.
- Trace a vectorized hash table probe and a spill decision.
Chapter 32 ended with Spark’s two execution styles: whole-stage code generation over rows, and vectorized readers that hand it column batches. Photon is Databricks’ third answer: a native C++ engine that runs vectorized, interpreted kernels over column batches, inside the same executors and the same Spark plans.
Photon is closed source. This chapter follows the one detailed public description, the SIGMOD 2022 paper by Alexander Behm and colleagues, section by section, and cites it as such.[Behm et al., SIGMOD 2022] Where the paper says Photon uses a Spark mechanism, the chapter shows the Spark code. Current product behavior comes from the Databricks docs and is kept in Databricks callouts. The simulator in src/sim/spark/photon.ts implements the algorithms the paper describes, with every gap the paper leaves marked as a simplification.
Why a native engine
Spark SQL’s whole-stage code generation (chapter 32) was the engine Photon set out to replace. The paper gives three kinds of reasons for leaving it behind (Section 3.2):[Photon §3.2]
- JIT limits. Generated code ran into limits on generated method size and code cache size. When it did, Spark fell back to its much slower Volcano-style interpreted path. The paper says wide tables with hundreds of columns hit this regularly in production.
- Garbage collection. GC performance was seriously affected on heaps larger than 64GB, and Spark already managed its off-heap memory by hand.
- Control. The team wanted explicit control over memory pipelining and custom SIMD kernels, which is hard to coax out of the JIT.
The second decision was interpreted vectorization rather than code generation (Section 3.3). The team prototyped both natively. The paper’s evidence is engineering experience rather than a benchmark: about two months to prototype aggregation in a code-generating engine, a couple of weeks in the vectorized one. Two lasting arguments follow from the design. Vectorized operators keep their boundaries, so each one reports its own metrics, where fused generated code is one opaque loop. And because the engine already dispatches dynamically to a kernel per batch, choosing a different kernel per batch (adaptivity, below) costs nothing extra. The paper concedes that code generation can do better on complex expressions, and lists hybrid approaches as future work (Section 7).
Photon is compiled into a shared library loaded by the Databricks Runtime and runs inside the executor JVM’s tasks, one thread per task like Spark (Section 3.1).
Q1. Which reasons does the Photon paper give for building a native engine instead of improving the JVM code generator? (Select all.) (select all that apply)
Q2. Photon chose interpreted vectorization over code generation. Which advantage does the paper credit most directly to that choice?
Column batches and kernels
A column vector is a contiguous buffer of values plus a byte vector that marks which values are NULL. It can also carry batch-level metadata, such as whether its strings are all ASCII. A column batch is a set of column vectors plus a position list: the indices of the rows that are still active (Section 4.1).[Photon §4.1]
A filter does not move data. It returns a shorter position list, and inactive rows stay in the vectors with whatever values they had (Section 4.3). The team tried the alternative, a byte vector of active flags, and found it worse for all but the simplest queries: with a position list, every later kernel loops over exactly the active rows.
Kernels are the inner loops (Section 4.2). Each is a C++ template, instantiated for its input types and for two flags: does the batch have NULLs, and are all rows active. The paper’s Listing 2 is a square-root kernel. A sketch of its shape, with the two lines that matter written as in the paper:
template <bool kHasNulls, bool kAllRowsActive>
void SquareRootKernel(const int* RESTRICT pos_list, int num_rows,
const double* RESTRICT input, const int8_t* RESTRICT nulls,
double* RESTRICT result) {
for (int i = 0; i < num_rows; i++) {
int row_idx = kAllRowsActive ? i : pos_list[i]; // no indirection when dense
if (!kHasNulls || !nulls[row_idx]) { // no branch when NULL-free
result[row_idx] = sqrt(input[row_idx]);
}
}
}
The flags are compile-time constants, so each instantiation is a different loop. With kHasNulls = false the branch disappears. With kAllRowsActive = true the loop reads input[i] directly, contiguous loads the compiler can turn into SIMD. RESTRICT tells it the buffers do not alias. The simulator’s sqrtKernel runs the same loop with the flags as arguments and counts the lookups and checks each variant performs.
Q1. A filter keeps 3 of 1,024 rows in a Photon column batch. What does it change?
Q2. A batch has no NULLs in the input column and all rows active. Which SquareRootKernel instantiation runs, and why is it fastest?
Batch-level adaptivity
The flags are not chosen by the planner. At run time Photon builds metadata about each batch and picks the kernel instantiation that matches, which the paper calls batch-level adaptivity (Section 4.6). Every kernel adapts to at least the two flags above. Other examples in the paper:
- ASCII strings. Many string functions have a faster path when every string is ASCII rather than general UTF-8, and Photon can compute and store ASCII-ness in the column vector. The
upper()microbenchmark in Section 6.1 shows about 3× over the previous engine. - Compaction before a probe. A filter can leave a batch sparse. Probing a hash table with a sparse batch pays the memory latency of each load without filling the memory bandwidth, while a dense batch issues many independent loads at once. Photon tracks sparsity and compacts selectively; on one TPC-DS query the paper measures about 1.5× (Section 6.4). It does not publish the rule for when a batch counts as sparse.
- Shuffle encoding. UUIDs stored as 36-character strings can be detected before a shuffle write and encoded as 128-bit values, cutting the shuffled bytes by more than half in the paper’s test (Section 6.4).
This is the per-batch variant of what the paper relates to Vectorwise’s micro-adaptivity (Section 7): the same operator, different loops, chosen from what the data looks like right now.
Q1. Why does Photon compact sparse batches before probing a hash table?
The vectorized hash table
Joins and aggregations use one hash table design (Section 4.4).[Photon §4.4] Entries are rows, not columns: during a probe each key has to be compared against an entry, and with columnar storage that is a random access per key column (Section 3.4). A row entry also lets one pointer stand for a composite key.
A probe of one batch runs as a sequence of kernels:
- A hash kernel computes the hash of every key in the batch.
- A probe kernel uses the hashes to load the entry pointer from each row’s bucket. These loads are independent of each other, which is where memory parallelism comes from and why dense batches help.
- The loaded entries are compared with the probe keys column by column. The output is a position list of the rows that did not match.
- A non-matching row whose bucket was filled advances its bucket index and goes around again. The paper uses quadratic probing. A row whose bucket is empty has no match.
// HashTable.probe in src/sim/spark/photon.ts (trimmed)
const bucket = keys.map(hashKey).map((h) => h & this.mask); // 1. hash kernel
while (probing.length) {
const entry = probing.map((r) => this.buckets[bucket[r]]); // 2. probe kernel: loads
let candidates = /* rows whose bucket is filled */;
for (let c = 0; c < width; c++) // 3. compare one key column
candidates = candidates.filter((j) => this.entries[entry[j]][c] === keys[probing[j]][c]);
// matched rows emit; filled-but-different rows advance: bucket += step++ ; empty = no match
probing = next; // 4. go again
}
Each round is one pass of the kernels over the rows still probing, so the work per round shrinks with the load factor. The paper reports the vectorized hash join at about 3× to 3.5× over the previous engine and aggregation up to 5.7× on its microbenchmarks (Section 6.1). Photon did not implement sort-merge join at the time of the paper; it runs equi-joins as shuffled hash joins, which can spill, where open source Spark defaults to sort-merge because its shuffled hash join cannot (Section 6.1).
Q1. In Photon's hash table probe, what happens to a probe row whose bucket holds an entry with a different key?
Q2. Photon is columnar, yet its hash table stores entries as rows. Why?
How Photon enters a Spark plan
Photon gets the physical plan that Spark’s planner produced. A conversion rule rewrites it (Section 5.1):[Photon §5.1] in the paper’s words, “we walk the input plan bottom up, starting at file scan nodes, and map each supported legacy engine node to a Photon node.” At the first unsupported node on a path it inserts a transition and leaves the rest to Spark. The paper states that it does not start converting again in the middle of a plan, so a supported node above an unsupported one stays in Spark.
- Spark file scan Produces off-heap column vectors.
- Photon adapter Hands the batch buffers to the native engine.
- Photon operators Run the supported part of the physical plan on batches.
- Transition to Spark Emit rows for the first unsupported operator above the pipeline.
Three node types appear at the edges (Section 5.2):
- The adapter sits at the leaf of every Photon plan. Spark’s own scan produces columnar data (chapter 31), off-heap in
OffHeapColumnVectors, and the adapter hands those buffers to Photon without copying, with one JNI call per batch. The paper measures a JNI call at roughly the cost of a C++ virtual call, about 23ns. - The transition is the last Photon node. It pivots column batches into rows for the row-based Spark operator above it. The paper notes that one pivot on top of a Photon plan costs no more than Spark’s own path, because Spark’s scan is columnar and has to pivot anyway; more pivots in a plan could cost more.
- Shuffles use Spark’s shuffle protocol (map outputs, the block manager, fetch) but Photon’s own serialization, so “a Photon shuffle write must be accompanied by a Photon shuffle read”. Broadcasts use Spark’s mechanism.
The Photon part of the plan is serialized to Protobuf, passed over JNI, and rebuilt as a native operator tree. Photon also takes part in adaptive query execution, exchange and subquery reuse, and dynamic file pruning (Section 5.5), which matters because AQE re-plans at every stage boundary (chapter 33).
The simulator’s convertPlan implements this rule. Our reading for joins, which the paper does not spell out, is that a two-child node converts only if both inputs are Photon.
Q1. A plan is Scan → Filter → Python UDF → HashAggregate, and Photon supports everything except the UDF. What runs where?
Q2. What does the paper say about Photon shuffle files?
Memory reservations and spilling
Photon and Spark share an executor, so they share Spark’s unified memory manager (Section 5.3).[Photon §5.3] Photon separates two steps:
- A reservation asks Spark’s memory manager for memory. Like any request to it, this can make some consumer spill, including another Photon operator (“recursive spill”).
- An allocation then takes memory from what was reserved. It never spills; Spark only accounts for what Photon reserved.
Hash join and grouping aggregation split each input batch into a reservation phase, where memory is acquired and spills are handled, and an allocation phase. Without that split, an operator could find its own hash table spilled while it was inserting into it. The paper contrasts this with engines that give each operator a fixed budget and let it spill only itself.
Which consumer spills is Spark’s policy, unchanged. The paper states it for Photon as: sort the consumers from least to most memory and spill the first one that holds at least the N bytes needed. Spark’s TaskMemoryManager.acquireExecutionMemory implements it with a TreeMap keyed by memory used:[TaskMemoryManager.java]
// TaskMemoryManager.acquireExecutionMemory (Spark v4.0.1, trimmed)
long got = memoryManager.acquireExecutionMemory(required, taskAttemptId, mode);
if (got < required) {
TreeMap<Long, List<MemoryConsumer>> sortedConsumers = new TreeMap<>();
for (MemoryConsumer c: consumers) {
if (c.getUsed() > 0 && c.getMode() == mode) {
long key = c == requestingConsumer ? 0 : c.getUsed(); // the requester goes last
sortedConsumers.computeIfAbsent(key, k -> new ArrayList<>(1)).add(c);
}
}
while (got < required && !sortedConsumers.isEmpty()) {
Map.Entry<Long, List<MemoryConsumer>> currentEntry =
sortedConsumers.ceilingEntry(required - got); // smallest that is big enough
if (currentEntry == null) currentEntry = sortedConsumers.lastEntry(); // else the biggest
List<MemoryConsumer> cList = currentEntry.getValue();
got += trySpillAndAcquire(requestingConsumer, required - got, cList, cList.size() - 1);
if (cList.isEmpty()) sortedConsumers.remove(currentEntry.getKey());
}
}
The comment in the source gives the two goals: minimize the number of spills, and do not spill more than needed. trySpillAndAcquire drops a consumer from the list once its spill call frees nothing.[trySpillAndAcquire] The simulator’s acquire ports this loop.
Large, long-lived state such as hash tables lives in memory Photon manages itself, which the paper says lets it handle large records more robustly than the Spark engine (Section 4.5). Off-heap memory is sized statically. Broadcasts are the exception that crosses into the JVM heap, since Spark’s broadcast copies the data on-heap (Section 5.4).
Q1. A Photon operator must reserve 150 MB; the pool has 80 MB free. Other operators hold 500, 300 and 120 MB. Which one is asked to spill first?
Q2. Why do Photon's hash join and aggregation split each input batch into a reservation phase and an allocation phase?
Photon on Databricks
The paper’s headline numbers are an average of 3× and a maximum of over 10× on customer workloads compared with the previous Databricks Runtime, and an audited 100TB TPC-DS record in November 2021 (Section 1). On TPC-H at scale factor 3000 it reports an average of 4× and a maximum of 23× (Q1, from decimal arithmetic), and Parquet writes about 2× faster, mostly from column encoding (Section 6). These are 2022 measurements against the 2022 runtime.
To check whether a query used Photon, read its physical plan or query profile: Photon nodes are named Photon..., and each place it returns to Spark shows a columnar-to-row transition. The lab’s first tab produces the same shape.
Q1. According to the Databricks docs, which of these keep a query (or part of it) off Photon? (Select all.) (select all that apply)
Try it
- Plan conversion. Pick “Python UDF in the middle”: the filter runs in Photon, a transition sits under the UDF, and the aggregate stays in Spark even though Photon supports it. Tick “pretend PythonUDF is supported” and the whole plan converts, with one transition on top. Try the sort-merge join plan: two transitions, one under each side.
- Kernels. With no filter and no NULLs, the kernel is the dense, branch-free one. Turn on NULLs, then filter
x > 100: the variant changes and position-list lookups appear. Turn on compaction and the batch shrinks to its active rows and the fast variant comes back. - Hash probe. Raise the table fill to 90% and watch the number of rounds and the “other key, advance” column grow. Add missing keys: they end at empty buckets.
- Spill choice. Ask for 150 MB: the 120 MB sort spills, not the 500 MB build side. Ask for 700 MB: the largest spills first because nothing covers the whole shortfall, then the smallest that covers the rest.
- HashAggregate count(*) by bucket
- Project bucket = my_udf(amount)
- PythonUDF my_udf(amount)
- ColumnarToRow
- PhotonFilter status = 'paid'
- PhotonAdapter
- FileScan orders
- PhotonAdapter
- PhotonFilter status = 'paid'
- ColumnarToRow
- PythonUDF my_udf(amount)
- Project bucket = my_udf(amount)
2 Photon nodes, 4 Spark nodes, 1 column-to-row transition. Photon Spark transition
Summary
- Photon is a native C++, interpreted-vectorized engine inside Databricks Runtime executors. The paper’s reasons: JIT and code cache limits on generated code, GC on large heaps, and control over memory and SIMD. Interpretation keeps per-operator metrics and makes per-batch adaptivity cheap.
- Column batches are column vectors with NULL byte vectors and a position list of active rows. Filters shrink the position list; kernels are templates over “has NULLs” and “all rows active”, chosen per batch at run time.
- The hash table stores row entries and probes a whole batch per kernel pass: hash, load, compare column by column, and advance the non-matching rows by quadratic probing. Sparse batches are compacted first to keep loads parallel.
- A rule walks the Spark plan bottom up from the scans, converting supported nodes, with an adapter at the scan and a column-to-row transition where Photon stops. Photon shuffles need Photon on both sides.
- Photon reserves memory from Spark’s unified memory manager before allocating, and the spill victim is Spark’s: the smallest consumer that holds the shortfall, else the largest.
History
Alexander Behm, Shoumik Palkar, Utkarsh Agarwal, Timothy Armstrong, David Cashman, Ankur Dave, Todd Greenstein, Shant Hovsepian, Ryan Johnson, Arvind Sai Krishnan, Paul Leventis, Ala Luszczak, Prashanth Menon, Mostafa Mokhtar, Gene Pang, Sameer Paranjpye, Greg Rahn, Bart Samwel, Tom van Bussel, Herman van Hovell, Maryann Xue, Reynold Xin and Matei Zaharia, all of Databricks, published “Photon: A Fast Query Engine for Lakehouse Systems” in the SIGMOD 2022 industrial track (Philadelphia, June 12–17, 2022).[doi:10.1145/3514221.3526054] The paper reports the audited 100TB TPC-DS result from November 2021.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 12 quiz questions.