Sub topic 2
Why columnar, vectorized execution is faster
This chapter explains the two ideas behind Photon's speed: columnar data layout and vectorized processing. It assumes you know basic SQL, can describe Spark stages and tasks, and have worked with Delta tables on Databricks. You do not need to know CPU internals, but a few terms are introduced as we go.
The problem with row-at-a-time processing
A classic query engine processes one row at a time. For each row it reads the needed fields, evaluates an expression, and passes the result to the next operator. This is simple, but it has costs that grow with data size:
- Function call overhead. Each operator calls the next one for every row. With a billion rows, that is a billion calls per operator.
- Poor cache use. A CPU is fast only when the data it needs is in its small, fast caches. A row holds many columns, and a query often needs only two or three of them. The rest of the row is loaded and then ignored.
- Branching and type checks. Generic code often asks "what type is this value?" for every row. These checks stop the CPU from running ahead efficiently.
The standard Spark SQL engine reduces some of this with whole-stage code generation. It compiles a pipeline of operators into one Java function. That helps a lot, but it still runs on the JVM and still works mainly on one row at a time.
Columnar layout
In a row-oriented layout, all the values of one row sit next to each other in memory. In a columnar layout, all the values of one column sit next to each other.
| Layout | Memory order | Good for |
|---|---|---|
| Row-oriented | `(id1, region1, amount1), (id2, region2, amount2), ...` | Reading or writing whole records |
| Columnar | `id1, id2, ...` then `region1, region2, ...` then `amount1, amount2, ...` | Scanning and aggregating a few columns over many rows |
Analytics queries usually touch few columns across many rows. For example, SUM(amount) needs only the amount column. With a columnar layout the engine reads just that column.
Columnar layout has three more benefits:
- Better compression. Values in one column have the same type and are often similar. Encodings such as dictionary encoding (replace repeated strings with small integer codes) and run-length encoding (store a value and a repeat count) work well on them.
- Less I/O. Parquet, the file format under Delta tables, is already columnar on disk. A query that selects three columns reads only those column chunks.
- Predictable memory access. Values of one type sit in a contiguous block, so the CPU can read them in order.
Parquet being columnar on disk does not mean the engine processes it in a columnar way. Older Spark paths often convert the data into rows after reading it. Photon keeps data in columnar batches through the pipeline.
Vectorized execution
Vectorized execution means an operator works on a batch of values at once, instead of one row at a time. A batch is typically a few thousand values from one column.
Consider the filter amount > 100. Row at a time, the engine runs the comparison code once per row. Vectorized, it runs a tight loop over a batch:
# Conceptual model only: this is not how Photon is implemented.
def filter_batch(amounts, threshold):
keep = []
for i, value in enumerate(amounts):
if value > threshold:
keep.append(i)
return keep
batch = [20, 150, 99, 400, 101]
print(filter_batch(batch, 100)) # [1, 3, 4]The Python above only shows the shape of the idea: one call handles a whole batch and returns the positions of matching rows. In a native engine, the same loop is compiled machine code with no per-value type checks. The operator is called once per batch, so call overhead is spread across thousands of values.
SIMD
Modern CPUs have SIMD instructions (single instruction, multiple data). One SIMD instruction can compare, add or multiply several values at once, for example eight 32-bit integers in a 256-bit register. SIMD needs the values to be packed next to each other in memory, which is exactly what a columnar batch provides. A row layout cannot use SIMD this way, because the values for one column are scattered between other columns.
CPU cache and branch behavior
A batch of a few thousand values fits in the CPU's cache. The engine loads it once and applies an operation to all of it. Tight loops with few branches also let the CPU predict what runs next and keep its pipeline full.
Native code instead of the JVM
Photon is written in C++ rather than running on the JVM. This matters for three reasons:
- Direct control of memory. Photon manages its own columnar buffers. It avoids creating many small Java objects, which reduces garbage collection pauses.
- Direct use of CPU instructions. C++ code can be compiled to use SIMD and other hardware features.
- No object boxing. On the JVM, generic code can wrap primitive values in objects. Native code works on raw values.
Photon plugs into Spark. Spark still plans the query, splits it into stages, and schedules tasks. Inside a task, supported operators run in Photon instead of the JVM code path. Chapter 1 covered that execution model, and the next chapter looks at what Photon accelerates.
Where the gains are largest
Columnar, vectorized execution does not speed up everything equally. It helps most when the query is limited by CPU work on data already in memory or on fast storage.
- Large scans with filters and aggregations. Few columns, many rows, simple expressions. This is the best case.
- Joins and aggregations over large inputs. Hash table building and probing run faster in native code.
- Wide tables where the query reads few columns. The columnar layout skips the rest.
It helps less when the time goes elsewhere:
- Waiting on storage or the network. If a query is slow because it reads too many files from cloud storage, faster CPU work will not fix it. Layout and data skipping, covered later, address that.
- Shuffles. Moving data between executors is limited by network and disk. Vectorization speeds the work around a shuffle, not the shuffle itself.
- Very small queries. Fixed costs such as planning and task startup dominate.
- Row-by-row user code. A Python UDF forces data out of the columnar format, as a later chapter shows.
Common errors in the mental model
- "Parquet is columnar, so Spark already does this." Parquet is a storage format. Whether execution stays columnar depends on the engine and the operators in the plan.
- "Vectorized means parallel across machines." Spark already parallelizes across tasks and machines. Vectorization is about efficiency within a single task on a single core.
- "Photon makes every query faster." The gain depends on where time is spent. Always measure, as the benchmarking chapter explains.
Summary of the working model
- Columnar layout stores each column contiguously, so queries read and process only the columns they need.
- Vectorized execution processes a batch of values per operator call, which cuts call overhead and lets the CPU use SIMD and its caches well.
- Native C++ code avoids JVM object overhead and garbage collection for the supported operators.
- The gain is largest for CPU-bound scans, filters, joins and aggregations, and smallest for I/O-bound, shuffle-bound or tiny queries.
Exercise
A query computes SUM(amount) over a 2 TB Delta table with 40 columns, and the Query Profile shows most of the time spent waiting to read files from cloud storage. Will turning on Photon be the main fix? Explain using columnar and vectorized execution.
Show answer
Probably not. Columnar and vectorized execution speed up CPU work on data in memory, such as filters and aggregations over batches. If the time goes to reading too many files, the bottleneck is I/O. Faster CPU processing leaves that wait mostly unchanged. Better fixes reduce the data read, such as compacting small files, data skipping through clustering, or filtering earlier. Photon may still help the aggregation step once the data arrives.
Exercise
Why can SIMD instructions be used on a columnar batch but not easily on a row layout?
Show answer
SIMD applies one instruction to several values packed next to each other in memory. A columnar batch stores values of one column contiguously, so they can be loaded into one wide register. In a row layout, the values of one column are separated by the other columns of each row, so they cannot be loaded together.