Beyond Manual Tuning: How RL Agents Learned to Optimize Apache Spark
Hina Gandhi34:492026
O padrão de 200 partições do Spark falha tanto em jobs pequenos quanto em jobs com skew
Divida um job de 1.000 linhas nas 200 shuffle partitions padrão do Spark e ele se afoga em tarefas vazias; aplique a mesma configuração a um job mensal com skew e surgem stragglers e pressão de memória. As equipes de dados respondem com rodadas intermináveis de ajustar e executar de novo. Hina Gandhi, Software Engineering Technical Leader na Cisco, apresenta um agente de Q-learning que escolhe configurações antes de o job começar. Mas será que o ajuste aprendido supera as correções em tempo de execução do próprio Spark, ou depende delas?
Conheça o design do agente, os números dos benchmarks e um modelo multiagente para um Spark que se ajusta sozinho
Hina Gandhi, Software Engineering Technical Leader na Cisco, mostra como um agente de Q-learning acoplado ao driver do Spark aprende a escolher configurações, como shuffle partitions, antes de um job ser executado. Ela defende que combinar essa inteligência pré-execução com o Adaptive Query Execution (AQE) do Spark supera cada abordagem isolada, relatando ganhos de 46% e 68,6% em seus experimentos, e propõe um design multiagente com um coordenador determinístico para memória, computação e cache.
“Então, exatamente a mesma configuração leva a problemas completamente opostos, dependendo do workload.”
“Se você tem só RL, você é inteligente de antemão, mas cego durante a execução. Se você tem só AQE, você reage bem, mas parte de, sabe, decisões abaixo do ideal.”
What you will learn
Explicar por que um padrão estático do Spark, como 200 shuffle partitions, paraleliza em excesso jobs pequenos e sobrecarrega jobs grandes com skew.
Projetar um wrapper de Q-learning não intrusivo que amostra um dataset, agrupa em faixas o tamanho, a cardinalidade e o skew, e escolhe configurações antes da execução.
Ajustar a exploração com um epsilon que decai ao longo do tempo, mas nunca chega a zero, para que o agente continue se adaptando a mudanças no código e nos dados.
Combinar decisões de RL pré-execução com o Adaptive Query Execution do Spark para obter ganhos de desempenho complementares.
Estruturar a otimização de vários parâmetros como agentes especialistas coordenados por um orquestrador determinístico simples, em vez de uma única IA monolítica.
Details
Level
Intermediate
Format
Tech talk
Technical depth
Practitioner
For
Mid-career, Senior individual contributor
Length
34:49
Published
June 2026
Questions this talk answers
Por que o Adaptive Query Execution não resolve sozinho o ajuste do Spark?
O AQE só entra em ação depois que o job começou a ser executado, então o custo de decisões iniciais ruins, como o particionamento, já foi pago. Ele pode corrigir o rumo, mas não consegue desfazer totalmente essa ineficiência.
Como o agente de RL entende um dataset sem deixar o job mais lento?
Ele amostra um pequeno conjunto de linhas (cerca de 1.000 no experimento dela, levando aproximadamente 100 milissegundos) para estimar tamanho, cardinalidade e skew, e depois agrupa esses sinais em faixas para que workloads semelhantes compartilhem as configurações aprendidas.
Quanto mais rápida foi a abordagem híbrida de RL com AQE?
Segundo a palestrante, em um dataset de 1.000 linhas com pouco skew, o híbrido rodou em 0,142 segundo contra 0,263 segundo do AQE sozinho (46% mais rápido), e em um dataset de 75.000 linhas com skew, em 0,143 segundo contra 0,457 segundo (uma melhoria de 68,6%).
Como vários agentes de aprendizado evitam conflitos entre si?
Cada agente (partição, memória, cache, núcleos) aprende de forma independente em seu próprio domínio, e um coordenador leve, que não é uma IA, aplica as decisões deles em uma ordem fixa e determinística, mantendo o sistema previsível e fácil de depurar.
Como uma equipe pode começar a usar essa abordagem em produção?
Comece de forma incremental: instrumente os jobs para capturar sinais de desempenho, adicione um wrapper leve de Q-learning para decisões pré-execução, mantenha o AQE ativado para adaptação em tempo de execução e deixe a infraestrutura aprender com o tráfego de produção ao longo do tempo.
Uma configuração do Spark, duas falhas opostas (82 s)
Reduzindo as partições de 200 para 8 (70 s)
Intuição aprendida encontra reflexos em tempo real (84 s)
Speaker: Thank you everyone for joining. Let's get started. So today I'm going to talk on optimizing performance with reinforcement learning. And yeah, so before we get started a little bit about myself, I am working as software engineering technical leader at Cisco. I'm leading large scale security solutions for our customers. Previously, I have worked at VMware and Cloudhead technologies where my main focus was leading backend solutions. And I'm currently serving as the chair of women in engineering, IEEE chapter for New Jersey Coast section. And I'm also the secretary of young professional chapter within the same section.
Speaker 1: Yep. So, yeah. So, so this is the problem we everyone have seen with large scale data system. The problem is performance tuning, especially like how we can move from manual tuning system, like Apache spark to system that actually learn how to optimize themselves using reinforcement learning. If you ever worked with spark, you have probably gone through cycles of tweaking configurations, re-running jobs, checking metrics, and then tweaking again. And even after all that effort, there is always this lingering feeling that, you know, maybe there is still, you know, better configuration out there that you just haven't found yet. That uncertainty is exactly what makes this problem so interesting. So the central question is, I want to explore today, you know, instead of relying on like human intuition and trial and error, can we build systems that learn from past execution and automatically improve,
improve like improve over time. So by the end of this talk, you know, we will go through why this problem is inherently hard and how reinforcement learning provides a compelling solution and what this means for the future of distributed system. So, so here, you know, we have like, you know, for Apache spark, there are, uh, shuffle partitions by default, the configuration is 200, which meant like, you know, it will, uh, will be like, you know, different for different situation.
Um, so, um, let's say in real world data pipelines, they're not consistent, they're dynamic and unpredictable. So if you look at the examples here, a small daily job with around 1000 rows, uh, suffers when we apply a static configuration, like 200 partitions, because we end up creating many empty or underutilized tasks. Instead of gaining like parallelism, we will like introduce overhead, extra scheduling, metadata handling and wasted compute.
So the system, you know, becomes inefficient by over parallel, like, you know, over paralyzing. On the other hand, a much larger monthly job with around a million rows and significant skew behaves very differently under the same configuration. Now, instead of underutilization, a few partitions become overloaded, leading to stragglers, uh, memory pressure and even potential out of memory failures.
So the exact same configuration leads to completely opposite problems depending on the workload. That's the core issue, you know, static defaults fundamentally break in dynamic environment. And this is what, you know, we call the tuning crisis. We are trying to apply fixed configurations to system where the workload is constantly changing. So if you see over here, you know, this is how the spark optimization works today and more importantly, what's missing.
So if you go on the left side of the slide, we start with the manual tuning, which is still surprisingly common in production systems. Engineers configure parameters like number of partitions, executor memory and shuffle settings by hand. So the problem is that this approach depends heavily on domain, you know, deep domain expertise. You need someone who understands both the workload and the infrastructure.
And even then, you know, it's time consuming and fragile. As soon as the data distribution shifts or workloads evolve, which they, you know, they will do event. Eventually those carefully tuned configurations break down, leaving teams constantly chasing a moving target. So the industry recognized this limitation, which led to like adaptive query execution or AQE, which is shown in the middle.
AQE is a significant step forward because it allows spark to adjust execution plans dynamically at runtime, such as like changing a joint strategies or rebalancing partitions based on, you know, actual data statistics. However, there is an important limitation. AQE only kicks in after the job has already started executing by the top. By that point, you know, the system has already made some initial decisions like, you know, task scheduling or partitioning that may be suboptimal, meaning the cost of the bad start has already been incurred.
AQE can correct course, but it can't fully undo that inefficiency. This leads us to the core idea on the right side of the slide. That is the missing layer of pre-execution intelligence. What we really want is that for the system to make smart decision before execution even begins. So we need to leverage like, you know, past runs to predict the best configuration, whether that's the right number of partitions, optimal memory setting or ideal parallelism.
Instead of, you know, guessing upfront or fixing issues mid-flight, we begin with the high quality initial configuration. And that's exactly the gap that reinforcement learning, particularly agent based, you know, approaches can fill by observing like, you know, past execution, learning the patterns and continuously improving decisions over time. The system effectively, you know, builds experience much like a human operator would.
So now that, you know, we have identified the gap, the missing pre-execution intelligence, the natural question is how do we build something that can learn the right configurations before execution starts? The approach here is surprisingly elegant. We introduced a Q-learning based reinforcement learning agent that acts like a pre-execution apprentice. Starting from the left, we have the raw data set, which could represent any Spark, you know, workload, such as an ETL pipeline, analytics job or batch process.
Before that data set reaches the Spark execution engine, we insert a lightweight intelligence layer, the RL agent. The importance, important point is that this agent is non-intrusive. It runs on the driver side as a wrapper and does not, you know, modify internal execution engine, which makes it practical from an engineering standpoint. Yeah. So if we try to like, you know, write something inside the purchase part that will be very complex and, you know, we might break the system.
But if we just build a wrapper on top of the purchase part, mainly a wrapper in the Apache driver that can, you know, help with, you know, learning these configuration, learning these experiments and eventually, you know, become start thinking like human beings. So, yeah. So conceptually, you can think of it like a junior engineer learning on the job.
It observed the data set characteristics, experiments with configurations like partition counts and learns from real execution feedback. So over time, it develops the intuition about which configurations work best for which types of workload. So this is where reinforcement learning comes in. The agent takes action, observes rewards such as job run time, updates a strategy. The powerful part is, you know, the perfect memory.
Unlike humans who may forget, you know, experiments or lose tribal knowledge, the agent retains what it learns, you know, tuning, turning like months of trial and error into persistent organizational knowledge. So once it has earned enough, it outputs an optimized configuration before execution begins and only then does the job move into this part. So instead of starting with guesswork, we start with informed, learned decisions.
Yeah. So how it will work, you know, now let's, you know, open that black box and understand how this agent actually works internally at a high level. This is a, like, you know, classic reinforcement learning loop, but adapted very cleverly for Apache or like, you know, Spark workloads. So instead of thinking about it as an extract RL theory, think of it as a three step decision system that happens before execution starts.
First, the agent perceives the state of the job. It does not scan the entire data set because that would be too expensive and would defeat the purpose. Instead, it takes a small sample around 1000 rows, which takes, you know, roughly like 100 millisecond and uses that sample to estimate key signals like, you know, data size, cardinality and skew.
So why, you know, why whole data set is not read because, because that will defeat the purpose of using reinforcement learning, because still, you know, you would, if you try to read whole data set, try to analyze all the rows, it will go through the shuffles, go through that, you know, maybe go through the join. And, you know, the pre execution, you know, you would not be able to gain, you know, you would not be able to gain, you know, if you try to do that.
And same and similarly, you know, your time duration would reach, you know, would, you won't be able to meet that runtime duration that you want to meet with the RL agent. So just taking a small sample to determine like, you know, whether, what type of cardinality this, you know, this particular data set is, I think minimum rows.
I think for my experiment, I just took, you know, a thousand rows, but for your experiment, you could even take like 10,000 rows, which can give you like, you know, good, like understanding of the data set. So the important idea here is that the agent does not need the full data set to make a good decision. It just needed like a representative snapshot.
So next, the agent encodes this information into a form it can learn from. So continuous signals like size or skew are converted into discrete buckets, which allows the agent to generalize across similar workloads. This matters because, you know, no two data sets are exactly the same. So if every job were treated as completely unique, the agent would never learn.
But by grouping workloads into categories like small and skewed or large and uniform, it can reuse, you know, knowledge from previous runs and build experience over time. So let's say if I have a data set of 10K and another data set of 10,001 rows. So it would be like, you know, it would be useless if we treat both these data sets like, you know, different.
So we can create the buckets that, okay, you know, consider the data size of 0 to 20,000 in one bucket, 20,001 to like 30,000 into another bucket and so on. So that, you know, we come up with the same configuration for these types of data set characteristics. So, you know, then finally, you know, the agent selects an action such as like choosing the optimal partition count.
And this decision is based on the queue table, which acts like a memory table storing what configuration worked best for similar workloads in the past. So, yeah, at the same time, the agent does not blindly choose only the best known option. It balances the exploitation, which means using what it already knows works, but with exploration, which means occasionally trying new configuration.
So that balance is crucial because workloads evolve and the system needs to keep learning instead of getting stuck with yesterday's best answer. So I think in reinforcement learning, there is an epsilon parameter that generally, you know, is set for the mathematical formula that we have. And in my experiment, I decided to, it was like, you know, earlier, it was like 70% times you would choose, you know, from your, you know, from your known experiments and 30 times you would do it, you would do the exploration.
So that was the, you know, formula I was going with. And, but, you know, it won't go down to 0%. It would, you know, keep, you know, it would, after performing like certain set of experiment, let's say 100,000 experiment, with each experiment that epsilon will degrade, like, you know, it will come down, maybe by 0.01 every time.
But, um, it will not go down to zero, it will like, you know, once it reached to 0.05, which is 5%, we will just, you know, be, uh, stick to that number. We will, uh, because we still want the agent to do the exploration, uh, because maybe, you know, we have changed the code and now, you know, uh, maybe the configuration that worked previously may, may not.
May perform as, you know, it was performing before, but the new, new configuration that agent can explore can perform better. So that's why, you know, the, the idea is that, you know, you never go to zero percentage, the exploration person, percentage should not be zero, but it should be like at some level that, you know, your agent keeps on exploring rather than, rather than just, you know, sticking to the Q learning values that it has, uh, uh, achieved from the past explorations.
Uh, yeah. So now that, um, now that we have seen the agent decides on a configuration before the execution. So now let's, uh, complete the picture and understand how it actually learns and improves over time, because without the learning, this would just be like, you know, fancy heuristic. So starting, uh, from where we left off, the agent has already observed the data set encoded this state and selected an action.
It now applies that configuration. So instead of like using a default, like 200 partitions, it might choose something very different, such as eight partitions based on like, you know, past exploration or past experiences. So this still happens as a lightweight rep rep rep before the spark joint, a spark job begins without modifying it, like, you know, spark internals internals.
So once the job executes, the most important part of reinforcement learning comes into the play, which is the reward signal. So the system measures actual execution time and uses it as feedback. So for reinforcement learning agent, they are like reward and penalty. So if you are getting positive reward, that means that experiment was successful. Otherwise, if you get negative reward, that means, you know, this experiment does not work in this particular environment or state.
Um, yeah, so the system measures like, you know, actual execution time and use it, uses it as feedback. Faster execution results in higher reward, while slower execution leads to lower reward. And this is powerful because, you know, it's objective directly tied to business value and does not rely on proxies or complex heuristics. We are optimizing exactly what we care about, which is performance.
So the agent then uses this feedback, um, to update its memory, especially the queue table. If a configuration performs, you know, well, the agent reinforces that decision. If it performs poorly, it reduces its confidence in that choice. So over time, you know, this allows the system to continuously refine its understanding, adapt to like changing workloads and avoid assuming that yesterday's best configuration is still optimal today.
Putting it all together, this creates a like closed learning loop. The agent observes the workload, chooses a configuration, executes the job. It performs, you know, measures performance, updates the memory, and the repeats the process getting better with every run. So in my experiment, I only have chosen reward as the runtime, like, you know, but, but we, but, you know, we can also consider other factors like, you know, memory, or like, you know, cost.
So all these can come to the reward formula, which, you know, which can better help, you know, agent to understand how, uh, what configuration to choose to keep, you know, everything, you know, perfect, like cost, memory, and the, uh, CPU, uh, runtime. Yeah. So now that, uh, we, uh, understand how the, our religion work, the next question is how it compares to what we already have.
And more importantly, what actually works best in practice to answer that three different approaches were benchmarked on same workload. So starting with the baseline, we have adaptive query execution or AQE only, which is what most modern, you know, Spark system rely on today. So AQE provides a runtime adaptation and can fix issues like skew or inefficient joint strategies, but it has like two key limitations.
It has no pre-execution intelligence and no ability to learn over time. So every job essentially, you know, starts fresh reacting only after execution has already begun. Next is the RL agent on its own, which introduces pre-execution intelligence and the ability to learn continuously from past workloads, allowing the system to improve over time. However, the trade-off is that it does not adapt during runtime.
So if something unexpected happens, like, you know, extreme skew, the system cannot adjust mid-flight. Finally, the hybrid approach combines the strengths of both RL, which provides like smart initialization before execution and EQE handles like, you know, runtime correctness. This results in the best possible starting configuration, continuous runtime optimization and ongoing learning across workloads. It is the only approach that brings, you know, together all three capabilities, pre-execution intelligence, runtime adaptation and self-learning over time.
So, yeah, now let's look at actual results because this is where things get interesting. This experiment focuses on like, you know, small data set. We just took like thousand rows with very low skew. Intuitively, this should be an easy workload. But in Spark, small data sets often suffer from something counterintuitive, which is over parallelization. By default, Spark might use something like 200 partitions even when the data is tiny, which leads to like, you know, hundreds of small, most empty shuffle files, unnecessary scheduling overhead and wasted compute resources.
Looking at how each approach handles this, AQE alone starts with the default configuration and only reacts after execution begins. So, the initial overhead from those unnecessary partition has already been incurred, resulting in a runtime of 0.263 seconds. With the RL agent, the system recognizes, you know, upfront that this is a small data set and proactively reduces partitions from 200 down to 8, avoiding like the shuffle explosion entirely and bringing the runtime down to 0.175 seconds.
About like, you know, the hybrid approach combines both using RL for the correct starting configuration and AQE for runtime adjustment if needed and achieving the best result at 0.142 seconds, which is like 46% faster than the baseline. So, the key takeaway here is that most of the gain comes from getting the initial configuration right. AQE alone cannot fix bad starting decisions quickly enough while, you know, RL prevents those inefficiencies from happening in the first place.
Yeah. So, now let's see, you know, how it performed for a large data set. So, I only took 75,000 rows data set. It can be like, you know, 1 million or more than that, millions of rows data set. But more importantly was the skew data. It had the skew data, which can, you know, impact the partitioning, like, because, you know, some of the data, some of the partitions can be skewed.
So, yeah, skew, as most of us know, skew is one of the hardest problems in distributed system because some partition become extremely large, while others remain small, causing, like, you know, few tasks to run into bottlenecks. So, this leads to issues like stragglers, poor parallelism, and even out-of-memory failures. So, starting with the baseline, AQE does help with skew by rebalancing partitions during execution, but it still reacts only after the problem has appeared.
So, yeah, so this leads to, like, you know, so sorry, as a result, the initial partitioning can be suboptimal, and some tasks may become, like, overloaded early, leading to a runtime of, like, you know, 0.457 seconds. With the RL agent, the system leverages past experience to recognize this as a high-skew workload and proactively adjust partition scaling before execution begins.
So, this prevents hot partition, reduces memory pressure, and leads to a more balanced task distribution, bringing the runtime, like, you know, down to 0.201 seconds, which is also, like, 56% faster. The hybrid approach performs, you know, best because it combines both strategy, like we saw in the previous slide. And here, AQE continues to adapt dynamically if skew evolves during, you know, execution.
And this combination proactive and reactive optimization results in a runtime of 0.43 seconds, 0.143 seconds, achieving 68.6 improvement over the baseline. So, yeah, so these were, like, you know, performed on comparatively, you know, smaller data sets, but you can see the significant improvements when we compared AQE and RL agent-only mode. And so far, we have seen in both the use cases, hybrid mode, hybrid mode has achieved, you know, better results than, you know, the single mode only, which can be AQE or RL.
So, yeah. So, yeah, so let's now take a step back and connect everything we have seen so far. At a high level, what we are building here is not just a better optimizer, but a new model for autonomous infrastructure. The key insight is that, you know, maximum efficiency does not come from a single technique. It comes from combining, like, two different strengths.
On one side, we have RL agent, which represents, like, you know, learned intuition. It uses past experience, historical patterns, and accumulated knowledge to make smart decisions before execution begins, eliminating structural inefficiencies and poor initial configurations, such as, you know, over parallelism on small workloads. On the other side, we have AQE, which represents, like, real-time reflexes. It does not rely on memory, but instead reacts to what's happening during execution, handling unexpected anomalies and hidden skew, and acting as a fail-safe layer to correct issues mid-flight.
So, you know, the reason why both are needed is simple. If you have only RL, you are smart upfront, but blind during execution. If you only have AQE, you react well, but start from, you know, suboptimal decisions. And when you combine both, you start smart and stay adaptive, which is what ultimately, you know, delivers the maximum efficiency.
And more broadly, this pattern goes beyond spark and points to a general design principle systems, you know, of the future, which will combine, you know, learning-based planning with rule-based execution safeguards, and not one or the another, but both. So, in that sense, you know, truly autonomous systems don't just react. They learn, anticipate, and continuously adapt. Yeah. So, up to this point, we have focused quite a bit on shuffle partition because they are one of the most visible and impactful knobs in SPAR.
But the reality is partition is just one dimension of a much larger optimization problem. In real-world systems, you know, performance depends on multiple interacting factors like partitions, memory, compute, and caching. And the key challenge is that these are not independent. Changing one directly affects the others. What we are effectively asking engineers to do today is understand all these dimensions, predict how they interact, and continuously retune them as workloads evolve.
That's not just difficult. It's exponentially, you know, complex. So, if you look at this diagram, each axis represents a different dimension. Partitions are only the starting point. So, you know, the first thing is that the memory misconfiguration can lead to out-of-memory failures, especially in, like, you know, join heavy workloads where you have shuffles. Even in broadcast join, you can have out-of-memory issues.
So, you know, and also, like, compute can be wasted, you know, if tasks are, like, you know, over-paralyzed and become input-output bound. And caching decisions when ignored can result in redundant computation. So, even if you get one dimension right, the system can still perform poorly because of misalignment elsewhere. The real challenge is coordinating all of these together as a system.
And this is exactly where learning-based approaches become powerful. Instead of trying to handcraft rules for every possible interaction, reinforcement learning can, you know, learn these multi-dimensional trade-offs directly from execution outcomes. So, what we have shown so far with, you know, partition tuning is really just the entry point. The bigger opportunity here is, you know, moving toward fully autonomous system that can optimize across all these dimensions together.
Because ultimately, you know, optimization isn't about tuning a single parameter. It's about managing a complex, you know, interconnected system. And that's where traditional approaches starts to break down. So, if we see, like, you know, if the future is, the future is about the multi-RL agents. And the next question becomes, how do we actually design a system that can handle that complexity?
One approach would be to build a single large monolith AI that tries to optimize everything at once. But in practice, that tends to be fragile, hard to debug, and, you know, difficult to scale. So, instead, what this architecture proposes is something much more modular and robust. A system of specialized domain agents, each focused on a specific aspect of the problem, all coordinated through a central controller.
So, at the central, we have a coordinator that orchestrates decisions across these agents. Surrounding it, each agent develops expertise in its own domain. For example, the partition agent continuously learns how to eliminate shuffle and metadata overhead. Much like, you know, what we have discussed so far. The memory agent, you know, focuses on managing resource pressure, monitoring things like, you know, garbage collection and rebalancing trade-offs between different data structures during execution.
The cache agent, you know, learns reuse patterns over time, deciding, you know, what data should be persisted to avoid redundant computation. And the core agent looks more holistically at compute behavior, balancing parallelism against input-output intensity to ensure resources are used efficiently. The key idea here is separation of concerns. So, instead of one system trying to learn everything, each agent learns deeply with its own domain and the coordinator ensures they work together coherently.
So, this makes the system not only more scalable but more adaptable because you can evolve or, you know, improve one agent without destabilizing the entire system. So, this takes us from a single agent optimization model to something much more powerful, a coordinated ecosystem of learning agents, each contributing to its overall system efficiency. And this is really, you know, where the vision starts to expand from optimizing individual parameters to building fully autonomous self-optimizing data platforms.
So, here, if you see all these, like core, cache, memory, partition, these are all agents, but coordinator is not an agent, it's just, you can think of an orchestrator that will orchestrate, you know, the jobs between these, all these agents. And then, what this slide is really emphasizing is how we make a multi-agent system practical and stable in a real-world setting.
The key idea here is decoupled specialization. So, each agent operates independently within its own domain, whether that's partition, memory, cache, or compute, and learns, you know, using its own feedback loop. So, instead of one system trying to optimize everything at once, each agent builds, you know, deep expertise in a narrow domain, maintaining its own learning model and continuously improving based on outcomes in that specific dimension.
So, now, the important question is, you know, if all these agents are learning independently, how do we prevent them from conflicting with each other? So, that's where, you know, that's where, you know, the coordinator comes in. And this is very intentional design choice. The coordinator itself is not an AI. So, like I mentioned, it's a lightweight orchestration layer that simply applies each agent's, you know, decisions in a fixed deterministic order.
And this keeps the, like, system predictable, debuggable, and easy to reason about while, you know, still benefiting from learning at the edges. So, result is that we call, what we call it is systemic harmony. Each agent contributes its expertise and those decisions naturally come into a full stack optimization of the workload. So, instead of tuning parameters in isolation or relying on fragile, you know, global logic, the system evolved as a coordinated set of specialists.
And because each agent is decoupled, you can, you know, improve or extend one dimension like memory optimization without destabilizing the rest of the system. So, this architecture, you know, gives us the best of both worlds, deep domain-specific learning combined with simple and reliable orchestration. And that's what, you know, makes large-scale multi-dimensional optimization not just, you know, possible but practical.
And on to our, like, you know, last slide. So, to wrap this up, I want to, like, you know, take a step back and focus on the bigger shift we are seeing in how data infrastructure is solving. So, the reality today is that big data systems have simply outgrown manual tuning and static heuristics. The scale, variability, and complexity of modern workload make it impractical for humans to continuously intervene and retune systems.
What used to work as a rule of thumb configuration no longer holds up in dynamic production environments. What we are moving toward instead is a fundamentally different model. One where infrastructure learns from experience, multi-agent reinforcement learning allows system to take what used to be months of costly trial and error and convert that into, you know, persistent, reusable knowledge.
Every job execution become not just a task but a learning opportunity. Over time, the system builds, you know, intuition about workloads, data patterns, and, you know, optimal configurations. And that knowledge, you know, compounds. And importantly, this isn't something that requires a massive overhaul to get started. The path forward can be incremental. You begin by instrumenting your jobs so you can capture meaningful performance signal.
Then you introduce a lightweight learning layer like a, you know, Q-learning wrapper to start making, you know, better pre-execution decisions. You keep systems like AQE enabled for real-time adaptability. And over time, you know, let your infrastructure continuously learn from production traffic, improving without, you know, manual intervention. So the key takeaway here is simple. We are like, you know, moving from systems that are manually tuned and reactive to systems that are autonomous, learning driven, and continuously improving.
And that shift is, you know, what we will define the next generation of data infrastructure. Yeah. Thank you, everyone. Any questions or anything we want to ask? I can see the chat if we have any questions. Okay. If not, um, if not, then have a nice rest of your day, everyone. I gave you back like five minutes and thank you.
Thank you for joining. Thank you so much.
Transcribed automatically; names checked against the speaker record. Select a time to jump there.
Article based on this talk
Um agente que aprende consegue ajustar o Apache Spark melhor que os padrões estáticos?
Hina Gandhi mostra como um agente de Q-learning trabalhando junto ao Adaptive Query Execution do Spark transforma meses de tentativa e erro em conhecimento que o sistema retém.
Em resumo
Configurações estáticas do Apache Spark raramente correspondem a workloads reais, e o ajuste manual não acompanha a mudança dos dados. Hina Gandhi, Software Engineering Technical Leader na Cisco, defende que um agente leve de Q-learning que escolhe configurações antes de o job rodar, combinado com o Adaptive Query Execution (AQE) do Spark em tempo de execução, supera cada abordagem isolada. Em seus experimentos, o híbrido superou o AQE sozinho em 46% e 68,6% em dois datasets de teste, e ela esboça como uma equipe de agentes especialistas poderia estender a ideia para memória, computação e cache.
Principais aprendizados
Como agentes de Q-learning aprendem com o feedback da execução de jobs para construir políticas de configuração
Por que a otimização híbrida de RL e AQE supera cada abordagem isolada
Uma arquitetura multiagente para escalar a otimização autônoma para todos os parâmetros do Spark
Estratégias práticas de implantação para ambientes de produção
Por que os padrões estáticos falham
Gandhi começa com um ciclo que todo usuário do Spark conhece: ajustar configurações, reexecutar jobs, verificar métricas, ajustar de novo e ainda se perguntar se existe uma configuração melhor. Seu exemplo são as shuffle partitions, cujo padrão é 200. Para um pequeno job diário de cerca de 1.000 linhas, esse padrão cria muitas tarefas vazias ou subutilizadas, adicionando overhead de agendamento e metadados em vez de paralelismo útil. Um job mensal muito maior, com cerca de um milhão de linhas e skew significativo, falha na direção oposta: algumas partições ficam sobrecarregadas, causando stragglers, pressão de memória e possíveis falhas por falta de memória.
"Então, exatamente a mesma configuração leva a problemas completamente opostos, dependendo do workload." (3:24)
Ela chama isso de crise do ajuste. O ajuste manual depende de profundo conhecimento de domínio e deixa de funcionar assim que a distribuição dos dados muda. O AQE foi um avanço significativo porque ajusta os planos de execução em tempo de execução, mas só entra em ação depois que o job começou, então o custo de um começo ruim já foi pago. O que falta, segundo ela, é uma camada de inteligência pré-execução.
Um aprendiz pré-execução
Sua resposta é um agente de Q-learning que fica entre o dataset bruto e o mecanismo de execução do Spark. Ele é deliberadamente não intrusivo: roda no lado do driver como um wrapper, em vez de modificar os internos do Spark, o que, segundo ela, seria complexo e poderia quebrar o sistema.
"Então, conceitualmente, você pode pensar nele como um engenheiro júnior aprendendo no trabalho." (7:21)
O agente funciona em três etapas. Primeiro, ele percebe o job amostrando um pequeno número de linhas (ela usou cerca de 1.000, o que leva aproximadamente 100 milissegundos) para estimar tamanho dos dados, cardinalidade e skew, porque ler o dataset inteiro anularia o propósito. Segundo, ele codifica esses sinais contínuos em faixas discretas, de modo que um dataset de 10.000 linhas e um de 10.001 linhas sejam tratados da mesma forma. "Então, se cada job fosse tratado como completamente único, o agente nunca aprenderia." (10:38) Terceiro, ele escolhe uma ação, como o número de partições, a partir de sua Q-table, a memória do que funcionou para workloads semelhantes no passado.
Aprender com recompensas, sem nunca parar de explorar
O agente equilibra o aproveitamento de configurações reconhecidamente boas com a exploração de novas. No experimento dela, ele começou com 70% de aproveitamento e 30% de exploração, com o epsilon decaindo gradualmente, mas mantido em um piso de 5%, para que o agente continue experimentando quando o código ou os dados mudam.
"Então, esse equilíbrio é crucial porque os workloads evoluem e o sistema precisa continuar aprendendo em vez de ficar preso à melhor resposta de ontem." (12:28)
Após cada execução, o tempo de execução medido se torna a recompensa. Execuções mais rápidas recebem recompensas maiores e reforçam a escolha; execuções mais lentas reduzem a confiança do agente nela. Gandhi usou apenas o tempo de execução, mas observa que memória ou custo também poderiam entrar na fórmula da recompensa. O resultado é um ciclo fechado: observar o workload, escolher uma configuração, executar, medir, atualizar a memória e repetir, melhorando a cada execução.
O que os benchmarks mostraram
Gandhi comparou três abordagens nos mesmos workloads: só AQE, só o agente de RL e um híbrido dos dois. Em um dataset de 1.000 linhas com pouco skew, o AQE sozinho rodou em 0,263 segundo. O agente de RL reconheceu o dataset pequeno e reduziu as partições de 200 para 8, levando o tempo de execução a 0,175 segundo, e o híbrido chegou a 0,142 segundo, 46% mais rápido que a linha de base. Em um dataset de 75.000 linhas com skew, o AQE sozinho levou 0,457 segundo, o agente de RL 0,201 segundo e o híbrido 0,143 segundo, uma melhoria de 68,6%, conforme ela relatou. Ela reconhece abertamente que eram datasets relativamente pequenos.
"Então, a principal conclusão aqui é que a maior parte do ganho vem de acertar a configuração inicial." (20:20)
Ela descreve as duas camadas como intuição aprendida e reflexos em tempo real: "Se você tem só RL, você é inteligente de antemão, mas cego durante a execução. Se você tem só AQE, você reage bem, mas parte de, sabe, decisões abaixo do ideal." (24:31) Ela vê essa combinação de planejamento baseado em aprendizado com salvaguardas de execução baseadas em regras como um princípio geral de design para sistemas futuros, muito além do Spark.
De um agente a uma equipe de especialistas
As partições são apenas uma dimensão. Memória, computação e cache interagem entre si, e acertar uma enquanto outra está desalinhada ainda resulta em desempenho ruim. Em vez de uma única IA monolítica, que ela descreve como frágil, difícil de depurar e difícil de escalar, Gandhi propõe aprendizado por reforço multiagente: um agente de partição, um agente de memória, um agente de cache e um agente de núcleos, cada um aprendendo em seu próprio domínio por meio de seu próprio ciclo de feedback.
Em vez disso, uma camada leve de orquestração aplica as decisões de cada agente em uma ordem fixa e determinística, mantendo o sistema previsível e fácil de entender. Como os agentes são desacoplados, um deles pode ser melhorado ou estendido sem desestabilizar os demais.
O caminho dela para a produção é incremental: instrumentar os jobs para capturar sinais de desempenho relevantes, adicionar um wrapper leve de Q-learning para decisões pré-execução, manter o AQE ativado para adaptabilidade em tempo de execução e deixar a infraestrutura aprender com o tráfego de produção. "Cada execução de job se torna não apenas uma tarefa, mas uma oportunidade de aprendizado." (32:56)
Assista à palestra
Beyond Manual Tuning: How RL Agents Learned to Optimize Apache Spark, de Hina Gandhi (35 minutos): https://www.womentech.net/video/beyond-manual-tuning-how-rl-agents-learned-optimize-apache-spark
Sobre a palestrante
Hina Gandhi é Software Engineering Technical Leader na Cisco, com ampla experiência no design de aplicações escaláveis e de alto desempenho, incluindo funções anteriores na VMware e na CloudHealth Technologies abrangendo microsserviços em nuvem, plataformas de big data e desenvolvimento SaaS. Ela foi eleita a Women in Tech Software Engineering Leader of the Year de 2025 e retribui orientando estudantes e ministrando palestras como convidada em universidades.
Perguntas que esta palestra responde
Por que o Adaptive Query Execution não resolve sozinho o ajuste do Spark?
Como o agente de RL entende um dataset sem deixar o job mais lento?
Quanto mais rápida foi a abordagem híbrida de RL com AQE?
Como vários agentes de aprendizado evitam conflitos entre si?
Como uma equipe pode começar a usar essa abordagem em produção?
Rascunho gerado com IA a partir da transcrição da palestra. Revisão editorial pendente.