Getting the Most Out of DLT: A Deep Dive on What’s New and Best Practices
Summary
- Declarative pipeline evolution: Michael Armbrust traces how Delta Live Tables simplify complex ETL—from manual Spark code to declarative SQL that automatically optimizes, scales and recovers from failures.
- Materialized views and streaming: DLT offers both materialized views for batch transformations and streaming tables for real-time pipelines, with automatic optimization that chooses the best execution strategy.
- Advanced patterns and escape hatches: The deep dive covers data quality expectations, CDC handling, streaming aggregations and procedural escapes for edge cases—equipping teams to build robust pipelines.
Getting the Most Out of DLT: A Deep Dive on What’s New and Best Practices

Talk by Michael Armbrust, Distinguished Engineer, Databricks
This deep dive covers advanced usage patterns, tips and best practices for maximizing the potential of DLT. Attendees will explore new features, enhanced workflows and cost-optimization strategies through a demo-heavy presentation. The session will also address complex use cases, showcasing how DLT simplifies the management of robust data pipelines while maintaining scalability and efficiency across diverse data engineering challenges.
Here’s more to explore:
Production ready data pipelines for analytics and AI: https://www.databricks.com/solutions/data-engineering
The Big Book of Data Engineering: https://www.databricks.com/resources/ebook/big-book-data-engineering-2nd-edition
See all the product announcements from Data + AI Summit: https://www.databricks.com/events/dataaisummit-2025-announcements
Chapters
0:00Introduction1:04Declarative Pipeline Evolution5:59Delta Lake and Transaction Log10:56LakeFlow Overview14:39Materialized Views16:50Enzyme Optimizer21:33Enzyme Benchmarks25:45Orchestrating Materialized Views29:54IDE for Data Engineering33:22Ingestion with Streaming Tables38:21Streaming Table State Management41:52CDC and Data Quality47:27Streaming Aggregations and Joins52:34Handling Data Retractions59:23AutoCDC and Advanced Features1:08:58Pipeline Expectations1:13:32DABs and Meta-programming1:18:54Procedural Escape Hatches
FAQs
How do declarative pipelines simplify data engineering?
Instead of writing procedural code that says 'how' to transform data, teams write declarative SQL that says 'what' should happen. DLT automatically optimizes execution, handles recovery and scaling.
What are materialized views and when are they used?
Materialized views in DLT compute once and store results, ideal for batch transformations. They auto-update based on upstream changes and support complex logic like joins and aggregations.
How do streaming tables differ from materialized views?
Streaming tables continuously process incoming data in micro-batches, ideal for real-time pipelines. DLT automatically manages state, checkpoints and recovery—simplifying streaming complexity.
What are data quality expectations and how do they work?
Expectations are conditions your data must meet—row counts, schema validation, null checks. DLT monitors expectations continuously and routes quality issues to quarantine tables for investigation.
Full transcript
0:00 Introduction
Good afternoon everybody. Thank you for coming. We'll just wrap up a few more people. Um I I have the privilege of introducing Michael Armbrust. A few any of you I hope most of you in fact all of you were part of the keynote this uh this morning which was which was certainly eventful to say the least. Um, very excited to uh have um talk to you about LakeFlow declarative pipelines. Um, if I can just ask you to fill out a survey at the end of the session, it really really appreciate it.
And we'll we'll we'll wrap it up with some Q&A afterwards, I believe. Go ahead. Thank you. Perfect. Thank you so much. So, I think the lawyers told me I had to put this up and uh this is not working. It's okay. Um, cool. So, and please do fill out the survey afterwards. Let us know how we can improve. Uh, today I'm going to do a deep dive into LakeFlow declarative pipelines. how you use it, how to use streaming, the difference between materialized views and streaming, some gotchas, some pitfalls, some escape hatches, uh, all of that kind of stuff, and then like he said, there will be time at the end for Q&A.
1:04 Declarative Pipeline Evolution
Um, cool. So, I just want to really quickly, I think probably most of you just saw the keynote, but I just want to recap kind of the idea behind declarative pipelines. Really, you know, since we started data bricks, uh, we've been trying to simplify the process of working with large scale ETL. And so Spark was the first step in this uh because it made it dramatically easier to leverage uh you know big clusters of thousands of machines.
Um but basically still the problem with Spark was RDDDs were an incredibly complicated API. Map produce is cute because it's functional and it makes it easy to do uh you know distributed computing handle failures and all of that kind of stuff. Uh but writing out things like joins and aggregations in map produce is actually incredibly complicated. And so the first thing we added was Spark SQL. And you know I'm going to be talking about declarative a lot today.
But the idea of declarative is instead of telling the system exactly how something is going to happen, instead of giving it a program or procedural code that says step by step what you need to do, uh instead you tell the system what should happen and the system figures out how to happen. So Spark SQL was one of the first projects I worked on in Spark and the key idea was we added this new thing called catalyst and we added the idea of a logical query plan uh to Spark and so now instead of just having RDDs that did these functional operations we had these kind of higher level relational operations filter project join aggregate and then all of the expressions that go along with that things like min and max and sum and average and then the catalyst query optimizer understands what all of these different operations do and that's actually the magic trick of declarative programming because it is not arbitrary touring procedural code which is you know very difficult for systems to understand in fact there's a whole theorem about the halting problem how it's impossible for a program to understand another program um the idea of declarative programming is because it's higher level the system can actually understand what is going on and that allows us to do optimizations on top of what's going to occur so with spark SQL we added the SQL interface we added the dataf frame interface All of it is powered underneath the covers uh by these logical query plans that get optimized and then planned into RDD operations.
And that was great. It dramatically simplifies using Spark. It opened it up to a whole new class of user. You no longer needed to learn Scala or Python. uh but still there was this problem that your data is constantly changing and usually if a query is interesting to you today it's going to be interesting you to you tomorrow and so you want to automatically keep those queries up to date and doing that in batch can be very difficult you have to worry about what data is new what data is old how you're going to remember what has been processed you have to the hardest case comes when there's failures because if something breaks in the middle did you process it or did you not process it so getting exactly one semantics can be very difficult uh when you're writing this batch code by hand and but with structured streaming we made this really simple.
We built it into Spark. We made it transactional. We made it very easy. We built all these different sources that understood how to read from things like Kafka and files and how to make sure that we process them exactly once. There's a bunch of really kind of cute tricks there where we we basically have a write ahead log where streaming writes down what it's going to do and then every sync is required to be item potent.
And so when you have a write ahead log plus item potence, you get exactly one semantics and the system can automatically pick up where it left off even if it failed in the middle and guarantee that you're always going to process that data exactly once. And so using streaming was pretty simple because you know it was exactly the same SQL and dataf frame API that we had before. The only difference is you're reading streams and structured streaming gives you this guarantee that anytime it gives you an answer, it will be the exact same answer you got if you ran a batch query over the same data set. just hopefully significantly more efficient because it's incrementally processing that data instead of reading it over and over again from scratch.
And so this was great, but as I said this morning, we kind of had a success disaster. As soon as we created structured streaming, I had a customer from data bicks come up to me and say he wanted to ingest billions of logs from all of their different security systems around the world. And he wanted to use streaming to do it and he wanted to write that data to S3. And I was like, well, we will definitely have no problem writing that data out.
But if you have millions of parquet files, many of them really tiny little parquet files, managing that in S3 is actually a nightmare. We had customers who had tables on S3 that were directories of parquet. It would take 40 minutes just to list all of the files in that directory. And so obviously the queries are incredibly slow then. And so the next thing we added was delta. And basically what Delta did was it's still the data stored in parquet, but instead of just having a directory of parquet files with no extra metadata, we added a transaction log to it.
5:59 Delta Lake and Transaction Log
And the transaction log allowed you to efficiently say for any version of the table, what files do I actually care about? And it enforced things like this is the schema of the table and you're not allowed to write to it if you don't match that schema. And this allowed us to build a bunch of higher level operations. update, delete, merge, the optimize command, which takes parquet files and collapses them and reorganizes them so that data is clustered in ways that allow us to do skipping.
We had statistics for every file. So we could play really cool tricks like when you're running a query and there's a predicate and we know the minmax values for every column in every file, we can say, well, of course this file contains no data and never even read the file, which made querying these large data sets dramatically faster. And so up until recently, this was kind of the Spark stack. Um, you know, and if you were a sophisticated Scola or Python programmer, you could do really cool things with it.
But there's this problem that taking your Spark code, the dataf frame stuff, which is like where we're actually getting value from our data, and turning it into a production pipeline is really complicated. So the thing in the center is the thing you actually want to be spending your time on. You have domain knowledge about your business. you understand all of the data that you're collecting, but you need to transform it so that you can use it for downstream things like AI reporting, business intelligence.
Um, but you're going to end up spending all of your time on other stuff. That code that I showed on the previous screen actually wasn't complete. It didn't actually manage the checkpoints for that stream, which are required so that you can restart it where it picked off it. If that stream failed, there was nothing to restart it. And restarts are actually really complicated. uh you don't want to you you need to make sure that you handle all kinds of different failures in the system.
We've seen a lot of uh cases where people failed at this in data bricks. You want to like first monitor each stream on the cluster. But let me tell you, occasionally you get a bad machine on Amazon and now that cluster even if you keep restarting that stream, it's just going to fail over and over and over again. So you actually need another process that is sitting off the cluster monitoring it making sure it's not in a bad state that can restart the entire cluster if restarting the streams isn't working.
And so you now you're starting to get into like distributed programming with watchd dogs and other stuff. Um dependency management, it's never just one table. It's usually hundreds of tables that depend on each other. And you need to make sure that you do things like create those tables in the right order. And so you end up writing a bunch of if this table exists, then create this table. If this column isn't there, then alter this table.
Um and so that you can automatically propagate new columns that appear through all the tables in your dependency graph. Uh also you often want to fan out and this was actually this was actually one of the key when we created uh declarative pipelines or DT many years ago. One of the first things we did was we collected uh support tickets from people who had said things were broken and this was one of my favorite because people would always create thread pools so they could run many different Spark queries in parallel and get the maximum utilization out of their cluster.
But unfortunately parallel programming is hard. they would often fail to catch those errors and pass them back to the main thread and then they would blame Spark and data bricks and we would have to go and read their code and be like actually you have a problem in your thread pool. Um and so you know this was one of the key motivations is you shouldn't be worrying about this stuff. And finally when you have a really complicated pipeline uh you don't want to be having one gigantic notebook.
You want to be able to spread that out, organize it, have different sources based on, you know, whether you're running in development or whether you're running in staging or production. And so you kind of end up building almost a compiler. And I have seen many people build ETL frameworks that are basically like compilers around uh around Spark. And this allows you to do proper CI/CD. And in a couple of slides, I'll talk about some patterns that where this is much easier with inside of DT.
And so this is why four years ago we created this thing called delta liveet tables or DT and you know this is a testimonial from one of our customers uh where they basically you know have been able to create data a bunch of users who were were not previously able to create data pipelines can now do it because we hit all the complexity you don't need to think about streaming you don't need to think about delta you just say these tables should exist and let the system figure it out for you so we have this simple intuitive declarative programming model um and so declarative pipelines is the next evolution of So all hinted at this.
There's a bunch of names flying around, but they really all mean the same thing. It's always been about declarative pipelines. I'm religious about not breaking APIs. So if you're already a customer of DT, do not worry. Your code will continue to work. Nothing will change. We're just rebranding as we we donate the project to Spark and as we expand it to work with tables that are, you know, maybe not stored in Delta as we can also write to Kafka and to Kinesis and PubSub and all these other things as well.
Um, and so the cool thing about declarative pipelines is you now can write end toend ETL pipelines in just a few lines of code. So this is a very simple example and I'll go through some more complicated ones in a moment. But you can see we're doing both incremental ingestion here streaming a bunch of files uh that are being uploaded to S3 or something. And then we're also doing incremental aggregation on top of it. I'm building this gold table that has a report about revenue by different regions over dates.
10:56 LakeFlow Overview
And I don't have to think about how that's going to be updated. I just say that result should be calculated. It should be stored in a table so that all of my dashboards can run super quickly and not have to recmp compute this every single time and not have to recmp compute every time new data arrives as well. And so all of this is part of this larger product called LakeFlow. I think one of the coolest things that has happened in the last year and a half is we used to have jobs and we used to have DT and they were totally separate and came in and said that doesn't make any sense and so he kind of reorged a huge chunk of the company and said work together build one product and so you're going to be seeing lots of really cool stuff rolling out over uh the next couple of months.
Uh pipelines, materialized views, streaming tables, they're all going to show up in that single list alongside jobs. A lot of features from jobs like the ability to do tagging and systems tables are now being built for DT as well. And so we're working really hard to make this all one single system. I'm going to be mostly focusing on the transform step here, declarative pipelines today. But just really quick, I want to talk about kind of the other parts of LakeFlow just so you understand how this fits into that context.
So you know the first step in any problem is ingestion. And you can do ingestion with DT. And in fact, DT is great at the kind of traditional type of spark ingestion where I have 10 million parquet files on S3 and I want to bring them into data bricks. Connect is for everybody else. It actually is zero code. You point andclick. You can go to different systems like Salesforce or workday or my SQL or Postgress and you say I want to ingest these tables.
I want to put them into this place in Unity catalog. And really what it's actually doing under the covers is it's creating a declarative pipeline. But it's a even a higher level of declarative programming where you don't even have to write SQL. You just say this table from here belongs here. Please make it happen. And that's actually one of the cool parts. Well, I mentioned that it's pointandclick it. You can also program it.
If you're familiar with DABs and you want to ingest 10,000 tables from some source system, you can create an asset bundle, you know, very similar to like Terraform and say, I want all of these things to be ingested. And you can use that to manage your lakeflow connect pipelines, but again with zero programming. The programming language here is JSON. And then on the other side, we have jobs orchestration. And so, you know, DT and ingestion and notebooks, these are all ways to accomplish some goal, but you don't want to do it just once.
And you don't want it to be someone's job to go and click run this notebook. And so, that's where orchestration comes in. when you want something to run reliably every day, every hour or even recently anytime new data arrives in some table or anytime data is uploaded uh you know into a directory. Jobs is responsible for triggering it, monitoring it, restarting it, doing timeouts, giving you graphs that show how the runtime has been changing over time and it can orchestrate everything.
So bal I think gave some examples this morning. Whether you're using data bricks notebooks, you're using declarative pipelines, whether you're running things in dbt or even on snowflake, you should be using jobs for all production orchestration because you know it's a it's a huge business. It's incredibly reliable. I think it's like 99. 99% uptime. So it's a very great way to make sure that everything happens reliably every single day or whenever it needs to happen.
Okay, so now that we've set the context, let's get into writing our first pipeline. So uh you know I think materialized views are the simplest way to think about declarative ETL. They've existed for a long time but we've extended them in a bunch of interesting ways in declarative pipelines. But before I talk about materialized views I need to make sure everyone in the audience understands what is a view. Uh so you know this is a basic database concept but it's super powerful.
14:39 Materialized Views
The idea of a view is I'm just taking a SQL query that I I want to run repeatedly or that I want to give to my co-workers so they can run it repeatedly and I'm just storing it in the catalog. So you can think of that name in the catalog for the view as a synonym for that query that you're writing. And so this is great because now we can standardize. We can share this. It provides a layer of indirection. If I need to change it, I don't need to go to everybody and tell them to change their query.
I just update the view and they'll start getting the new answer. So views are an incredibly powerful abstraction and you can also use them inside of declarative pipelines. You would use them in cases where you want to reuse that query over and over again. But here's the key detail. Views can be inefficient because there is nothing there. Views are a purely virtual concept. Nothing is stored. So every time you query a view, even from in the same pipeline, you are recmputing that result from scratch.
And so if it's something very simple, if you're just doing filters and projects, maybe that's actually okay. You don't want to pay the cost to materialize this data twice. Views are basically free. They're great ways to break your code up. But if it's a really expensive result, you don't want to be recmputing it over and over again. And that's where materialized views come in. So the word materialized in this context means we're going to store it.
So now when you query revenue by region, you're reading an already computed answer. And that means your dashboards, your AI training, whatever you're doing downstream can be super fast. You could start getting seconds latency to query this, even if it's actually a huge amount of data because we're doing a bunch of work ahead of time to precomputee it. And so here we actually have our first pipeline. You type this line of code into DBSQL.
Hit enter. You are now an ETL engineer. You have built a production pipeline. Pretty cool. Um, but you might say, okay, well, what's actually happening under the covers? Like, I could have just done this with a create or replace table and I would have gotten the same thing, right? So, let's talk about how enzyme uh works under the covers in order to efficiently and incrementally update these materialized views. So, Enzyme is an extension of Catalyst uh which is the query optimizer inside of Spark SQL and it's going to figure out how to update these materialized views uh most efficiently.
16:50 Enzyme Optimizer
So, you know, data is always changing and if I was using create a replace table instead of a materialized view, one row would be added to the input table, but then the entire table would be recmputed, even all of the rows that didn't change. The idea of enzyme is we're going to be a little bit smarter about this. when one new row arrives, well then we will just write one new row to the output. Now, I'm simplifying it quite a bit though because it actually turns out there's a bunch of different types of queries depending on the types of queries, the types of changes, the types of data, the information that we have from upstream.
There's actually several different techniques that you might want to use to do incrementalization. And again, this is why decorative programming is so powerful because you could handcode all of this stuff, but then maybe the table size upstream changes and now it's a different strategy and you'd have to rewrite it from scratch. Whereas a declarative program will kind of figure that out for you and we'll talk about how.
So how does Enzyme uh incrementally refresh different types of queries? Well, let's start off with the simplest one. It looks a lot like streaming. Uh and the idea here is when you have a monotonic query. So a monotonic query is one where it doesn't remove any tupils or any previous output with the addition of a new tupil. So you know if you're thinking about this in like original Spark terms, it's like a map only job.
One row comes in, one row comes out. You're allowed to do filters and things like that as well, but like there's no outer joins, there's no aggregations, there's nothing where a new result will change an existing result. And so in these cases, we'll actually just do the simplest thing. You end up with a system that looks a lot like structured streaming because all it's going to do is figure out what the new data is, run the transformation over it, push it downstream.
It works for select, project, interjoins, these these monotonic types of queries. But there's a key detail. You know, the query has to be monotonic and the input has to be monotonic. So it will not work if there are changes. So obviously enzyme needs to be more sophisticated than streaming and it can't only do this stuff. And so another strategy and this one's probably very familiar to anyone who's a data engineer in the audience uh is partition recomputation.
So this is I would say probably the most universally used way of doing incremental compute in like a traditional system like Spark or Hadoop. You break up all of your data by date and then you know you when data changes you only recomputee the date that changes. So some new rows come in we update only that partition. And this is great because now we can actually handle aggregations. Uh we can handle updates. If something's deleted, we just recomputee that partition and you're still getting the correct answer.
So this is actually really powerful. But if you have a really big date and one row changes, it's still not the most efficient way to do it. And really the biggest restriction here is these tables have to have exactly the same partitioning. So, it's great for those bronze and silver tables where everything is partitioned by date. But when you start getting to gold and you've aggregated by region or by business or something and you can no longer partition by date because you know a single record is aggregating over multiple dates, this technique no longer applies.
And so then there's another technique called replacing. And so this one is using techniques from database literature to compute changes to the results. So some rows come in, we figure it out. We, you know, basically we need to add 17 here. Uh, and so then all we do is we'll actually, there's actually two techniques here, and I'm kind of oversimplifying it a bit, but you're either replacing individual rows, recomputing that entire group, or you're doing a merge.
The really cool thing about merge is I can actually look at the target data. I can write this expression that says, you know, the new result is the current result plus the extra data that has come in. And so again, enzyme will pick between these two options depending on on what makes most sense. But this is this is super powerful because now you can handle pretty much arbitrarily complicated queries. Uh you can handle updates, deletes, and inserts efficiently.
But merge is pretty expensive. It requires reading a significant part of the target table. Uh so you know you don't want to use this if your quer is monotonic. It would be much more expensive. Uh and it's pretty complicated to reason about. we're now in the like implementing an outer join when both sides are changing incrementally requires quite a bit of relational algebra to get it correct. Um, and so I I don't recommend it for the faint of heart.
And so the question is, okay, Enzyme has all of these different techniques. How is it going to decide at any time which technique it's going to use? So enzyme is this optimizer. So, it's building on this framework that we already have with Catalyst where we can rewrite query plans, reason about their cost, and it's adding this new magic trick to it. Now, instead of only thinking about the query plans today, it's integrating directly with the Delta transaction log and this the change data feed and row ids and all of these great features that are coming from Delta that tell us exactly what data is changing.
21:33 Enzyme Benchmarks
And it's then deciding between all of these different techniques for every query and saying which one is the cheapest. Because there's something really interesting here. You might say, I never want a full recompute. Full recmputes are really expensive. But if 75% of your input data changed, it might actually be faster to full recomputee. And so if 1% changes, well, then it's definitely faster to merge. And the nice thing with enzyme is you don't have to think about that.
You don't have to statically code it. Enzyme will figure this out dynamically for you. So it'll pick the optimal update technique and take care of it. Now, Enzyme is doing some pretty cool tricks under the covers. It turns out not all queries are easy to incrementalize. Sometimes you actually have to rewrite the query to make it easier. So here I have an example of let's say I did select countd, you know, reading from some input table.
Well, how are you going to keep track of the distinct? I don't want to have to scan the entire input and do a distinct every time something changes. And so what Enzyme can do is it's going to use this technique called decomposition where it's actually going to take a single query that's complicated and break it up into multiple queries under the covers and those smaller queries are easier for us to incrementalize. So if you think about it with a distinct, another way to calculate a distinct count would be to actually calculate a count group by the thing you care about.
So for every customer ID, I'm going to remember how many records I saw. Remembering that count is critical because it what it's what allows us to do incremental. When I see a new record, I add one. When I see a record get deleted, I delete one. If it ever goes to zero, well, that customer doesn't exist anymore and so shouldn't apply to my distinct count anymore. And so now calculating the distinct can be done incrementally.
And when I want to get that final answer, all I need to do is count the number of rows in this table. So I update this like relatively simple group by query. I count the number of rows in this table and I get an incremental distinct which is pretty powerful. And doing a count like that is super fast because you can do it purely with delta metadata. You don't even need to scan the information. And so this is part of the trick.
And what's going to happen here under the covers is in Unity catalog we're actually going to create multiple delta tables. These hidden tables called materializations. And then the materialized view will actually be a view that sits on top and calculates the actual answer that you're looking for. And the nice thing is you don't need to think about any of this. This is all kind of just for your own edification. Uh all you need to know is when I query that materialized view, I will always get the correct answer no matter what changes have happened or you know how it's broken the query apart.
You're letting the system handle that for you. And we have been doing a ton of work. We announced Enzyme last year, but at the time it was pretty basic. It could only handle a couple of queries. Uh, in many cases it wasn't faster than doing a full recmputee, but we have done tons of work on it in the last year. We're now having quite a few success stories where it's saving customers lots of money. So, I want to talk about a benchmark that we just did last week.
We're basically running a variant of TPCDS, but converted to uh be based on reading from an MV instead. uh and you know for each incremental run we were adding or changing about 3 to 5% of the input data and then we were running normal TPCDS versus incremental materialized view TPCDS and as you can imagine this is a perfect use case for enzyme it's up to 19% better in terms of compute performance even with the added overhead of doing a merge and all that kind of stuff and what's really cool is as I mentioned at the beginning you never run these things only once you're going to run them over over and over and over again.
So these these savings will compound every single day. Running the full recomputee scales linearly as the data goes up, but the incremental compute is, you know, much closer to the amount of data that is changing. And that's pretty cool. Okay, so now let's talk about, you know, we've created our first pipeline. We created a materialized view. It's doing all this cool incrementalization for us, but how do I control how often it updates?
25:45 Orchestrating Materialized Views
How do I think about costs? Um, and so this is where uh, you know, basically when you first create a materialized view, materialized views in data bricks are by default snapshot materialized views, which means they're correct as of some moment in time and they will only update when you ask us to update them. And this is because we don't want there to be big performance cliffs. We're often working with big data. The update can be expensive.
So you get to pick the latency and cost trade-offs that you're working with. You could do this manually by running a refresh command, but really this is only for debugging. What pretty much all users do is they're going to use a schedule. And so the idea here is all I have to add is one extra line to this command. Schedule every one day, every two hours, whatever your latency targets are. And now it's not only going to create this materialized view in Unity catalog, but it's also going to create a job using data bricks uh you know, LakeFlow jobs under the covers.
And you know, this will automatically refresh this. It'll do retries. It'll do all the things you need to keep this thing up to date at the schedule you've asked it to do. But fixed daily schedules, you know, that's actually kind of brittle. The problem is like, you know, if I pick one day, well then, you know, in expectation every time I query this, it's going to be half a day out of date. And you know, it's going to also spin up that refresh every day, no matter what, even if the inputs haven't changed.
And that's why I am super excited about this new feature that is just being rolled out in u um in jobs which is triggers. So now instead of having a fixed schedule where you just say once a day do this no matter what uh the system's smart. It's actually going to read through this query plan. It's going to find all of the tables that you're querying from and as long as they're tables managed by Unity catalog we're going to monitor those tables and we're going to say let me know when these tables change.
And this way that materialized view is going to be triggered only when the inputs have changed and it'll be triggered immediately. So this is a really great way to save costs while still getting really good freshness on your materialized views. This feature is currently in private preview. I encourage you to go and sign up for it. The key thing you need to do to make it work is you need to make sure you have the right Unity catalog permissions set up because we need the ability to create notifications on all of your buckets so that we can get notified when tables change. so that we can set this up.
So, I know maybe you're not Unity catalog admins, but please go to your Unity catalog admins, enable uh the cloud metadata service because it is amazing. So many features are much better with it, including triggers. So, now it triggers immediately only when updated. But what if I have a table upstream that is just constantly being updated? I maybe don't want to pay for this materialized view to get refreshed every minute over and over again.
I'm only going to look at it every morning or you know I or it's actually just not that important if it's a couple of hours out of date. I'd rather save money. That's why we also have cost controls built into this. So in addition to saying trigger an update, you can also optionally say I only wanted to update this often. So this gives you a really nice way to bound the expected latency and the expected cost together all in one declarative statement.
So now we really do have I would I would argue these few lines of SQL. This is a complete production pipeline that we have built that is reliable. It moderates costs. It manages these triggers automatically for you. And so this is a pretty cool end toend example. So to simplify or just to summarize here, materialized views are a great way to premputee results and update them incrementally. They can be automatically updated whenever any of their inputs change while still controlling costs.
And the magic is it's all running on this serverless infra. So failures, retries, vertical, horizontal autoscaling, all these things are managed by the platform. They're not something you have to think about. So if your materialized view one day is tiny and then the next day is 10 times as large, you're only paying for the capacity that you're using here. The system is automatically figuring out what needs to happen.
29:54 IDE for Data Engineering
Okay, so now I want to talk about one of my favorite announcements from this morning, the IDE for data engineering. So creating, you know, as we just saw, creating one-off materialized views, these these materialized views that you create in DBSQL where you're just creating one table with one command, it's super easy and you can chain them together as you just saw with triggers. If I create a materialized view that depends on another materialized view, triggers will make sure that it updates automatically when the upstream materialized view changes.
So you actually can build graphs of dependencies kind of automatically in an ad hoc way. But I think any data engineers in the audience are cringing like do I really want to do my production data engineering in a SQL box? Like should I be using version control? How am I going to keep track of what depends on what? What if I change something and it breaks something downstream? And so most data pipelines look a little bit more like this.
There's hundreds of tables. They depend on each other. You want to make sure when I change something in bronze that I'm not breaking everything downstream. And that's why we created the ID for data engineering. This is, I think, a game-changing innovation. In just the last year, you know, before you were developing DT pipelines in notebooks, and it was a really brittle, awkward experience. It didn't feel right because you couldn't really run them.
The ID for data engineering changes all of this. It lets you develop an entire pipeline containing many related data sets all in the context of this really powerful editor that understands the context of the pipeline. So side by side with the code you get to see the graph. You get to see errors in line as you type. You can refresh individual tables and see the results all without any context switching. Uh we have support for Python, SQL and someday Scala.
And this is really how you start I think doing what I would call proper data engineering where your code is version controlled. It's checked into Git. You might be doing CI/CD. So this is why I think pipelines are so powerful and the ID is the way to edit these pipelines most efficiently. So getting started is super easy. We've actually built it into the workspace. You need to enable a few things in the previews. Uh but this is going to be rolling out broadly in the next couple months, but it's all available to try out today.
Uh you just click new ETL pipeline. It brings you to this really cool new screen where you can pick the catalog that you want to be working in by default. But this is now just a default. DT pipelines can write to many different tables and many different cataloges and schemas. Um but this is like the default. Think of it like typing use in DBSQL. setting where you're going to be reading and writing from. Uh, you know, if you don't give a qualified identifier, there's sample code built in.
So, if you're new to pipelines, uh, and you don't know the syntax, you can just start with some sample code for some common use cases and then just modify it for your particular use case. The, uh, the AI assistant is built into it, so it will help you write code as well. I've got a really quick video where we walk through it. So, you can see we can click on the graph, we can see the data right away for each individual table.
Um when we click on different nodes uh you know we're we're able to expand the graph and see all of them at once. We can actually go and see the metrics from the last execution of this pipeline. Um you can jump to the code for any particular table. So we're now encouraging you to have this pattern where you put every table in a separate file so you can organize your code better. You don't have to. It's just a convention, but this makes it really easy to jump around then and get to those files efficiently.
Um, you can once you change something, you can just click and refresh, which I think is pretty cool. And so I'm super excited about this. I really encourage you to change it. I think we've been doing a bunch of interviews with customers and this is like uniformly the most popular feature I've ever heard. Like everyone has just said this is this changes my life. Um, okay. So now we've done materialized views. We've talked about pipelines of materialized views, but sometimes the data isn't already in data bricks and you want to ingest that data first.
33:22 Ingestion with Streaming Tables
And materialized views aren't great way to do ingestion because materialized views are always the exact answer of the data from the input. You could read a bunch of files with materialized views, but then when you want to do retention and cleanup, if you delete that data from the input, you're deleting that data from the materialized view. And that's usually not what you're looking for with ingestion. And so this is where streaming starts to come in.
And so with streaming, we have to introduce a couple of extra concepts. So there are streaming tables and there are flows. And I want to dispel a myth that I hear quite a bit. Streaming tables are tables. There's a few gaps still, but I I think within the next few months, every single command you can run on a manage table in Unity Catalog, you will also be able to run on a streaming table. The goal is for them to be exactly the same thing.
And under the covers, they are just delta tables. There's a little bit of magic that we have to kind of do some plumbing for. I'll talk about that magic in a little bit. Um, but streaming tables are tables. They're exactly the same as manage tables. The only difference is you have a flow writing to them. A flow is our generic name for data moving through the graph. It could be a stream, but it could also be a batch query that only runs one time or it could be something that's updating a materialized view.
So, it's just a generic word for data movement. When you look at that graph from the previous screen, it's the lines in between the different tables. So a flow transforms data, writes it to some target. When it's used with streaming, that flow is how the checkpoint is managed. And so creating a streaming table and flow is pretty simple. We just have these two different commands. Create streaming table. And really the only difference here between a normal create table is you'll notice I'm not specifying the schema.
You could if you wanted to specify the schema here. And when you do, then we're going to enforce that schema. The system will make sure that we follow exactly what you're asking for. But oftent times I don't want to write the schema out twice. And I also have this flow that is reading from Kafka and doing some schema inference or something. And so if you don't specify the schema, then the system will automatically figure out what it should be and set up that table for you based on the flows that are writing into it.
So this is the long form, but of course almost every single time you're going to be creating a table and creating a flow. So we have some shortorthhand for this as well. When you say create streaming table as select star from whatever that is exactly the same thing. These two are syntactic sugar for each other. Uh there's no difference between them. Uh it's just a a convenient way to create a streaming table and a flow with the same name.
But as you'll see for more advanced use cases, sometimes you actually want to specify the flows separately. Um and then as I mentioned things like Kafka offsets are attached to that flow name. So if I create a new flow name I get a new checkpoint. If I use the same flow name I get the same checkpoints. That's how we reason about this is the same query across many executions of the same pipeline. So using streaming tables for ingestion is super cool.
We've got this really powerful data source called autoloader. You access it with cloud files or read files and it ensures exactly once ingestion using all kinds of low-level tricks to work with all of the different cloud provider storage systems S3, ADLS, GCS. It will register notifications. It will get them from Unity catalog so it can discover new files without listing out all of the directory. It has a instance of Rox DB that it keeps on the driver to keep track of which files have been ingested transactionally and then hands them off to structured streaming to do the actual ingestion.
It supports schema inference and schema evolution. And I really think the most powerful thing about autoloader is it really works at any scale. Data bicks's largest customers ingest pabytes of data every single day with autoloader. It is like rock solid. It's it's super cool. It's a great way to get data into data bricks. But sometimes you've got data in another system like Kafka and that works just as well. And you'll notice I've switched to Python here.
I mostly have been showing SQL syntax, but everything that I talk about today can be done in Python. It can be done in SQL. We really try to keep the languages equivalent to each other. It's really kind of your preference which language you want to be writing in. There are of course some things that you can only do in Python today until we get better procedural support. Um but for in most cases you should pick the language that you want to program in.
But just for variety we're talking about how to ingest from Kafka up here. And so you know in this case the Kafka source is automatically tracking which partitions and offsets have been ingested. You can use any structured streaming source that is in DT. You notice I'm using just the standard uh Spark readstream. Any any source that works there uh you know should work. And message buses are great when you want the lowest latency.
So when you're ingesting lots of data, message buses are this really nice low latency buffer to get that data in. Now as soon as we start talking about streaming though, you have to start thinking about it. Materialized views were simple because there's really only one thing you need to know. The query that I wrote is the answer that I'm going to get. You don't need to think about anything else. But streaming is stateful.
38:21 Streaming Table State Management
It remembers what data has been read. And what that means is it's promising that it's never going to read the same data twice. And that's great for performance. It means you don't need to worry about making a change and it going back and reprocessing. If I change the definition of a materialized view, it's going to recomputee from scratch because it has to update the table to match the new query you wrote. But with streaming, if I make a change, so let's say, you know, I changed this from a plus one to a plus 2.
Those rows that have already been processed are not going to be reprocessed. Only new data that comes in after I made the change to the code is going to have this change in the result. And so this is great because I think, you know, often you don't want to go back in time. That data's already been processed. It's too expensive. I have pabytes of data. But it's definitely a sharp edge. You need to be aware of this when you're using streaming.
If you do want to reprocess, sometimes you're like, "Actually, there was a mistake. It's important to the business to fix it. I'm willing to pay for a recomputee." Well, this is a nice thing that DT does because it automates it. In traditional structured streaming, you'd have to worry about creating a new checkpoint. You'd have to worry about clearing out the table. This is another thing we got tons of support tickets around in the past where people did it wrong and then had duplicate data in their table or or drop data or something like that.
Full refresh makes it dead simple. All you do is either type uh refresh the name of the table full or you go into the UI and you click full refresh or you can do this through the API as well. And what a full refresh does is it think of it as like I am starting the pipeline from scratch. So it clears out the contents of the table. It deletes the schema of the table. So if there's columns that you want to get rid of, they're now gone.
It clears out the checkpoints. So now the system is going to read from the beginning of time. Um, but it's important that whatever system you're reading from still has that data. If I am reading from like autoloader and I set a retention policy on that S3 bucket and the data is gone, well then it's gone forever. So there is also a config that you can set on this table to protect it. So that even if you ask it to do a full refresh, it won't.
Uh, that is I think it's like pipelines. reset. allow equals false. Um, so just something to be aware of. But full refresh is the way to say reprocess from scratch. And now here's a use case where you might actually want that more verbose syntax where you're specifying multiple flows. So if I want to ingest from many different Kafka instances and they're actually going to be changing over time. So you cannot change the number of sources and syncs in a structured streaming query.
The way structured streaming works is it takes the query plan that you wrote and it does a traversal order to find all of the leaves and then that order is the order that it expects to find the information in the checkpoint. If you reorder them, if you add new ones, streaming blows up and says, "I don't understand how to restart this query. This is a different query than before." And so multiple flows allows you to work around this because you have multiple streams each with their own checkpoint.
You can add or remove flows from the pipeline without any problems. And so this is a great way to do these more complicated ETL pipelines where you need to collect data from many different places or where you're evolving. You know, the upstream from you is doing a migration from one Kafka instance to another and we need to change it. Multiple flows are all very powerful ways to take care of that. So we talked about the easy cases where you're just ingesting new data, but I also want to talk about the one-off cases because the world is messy.
41:52 CDC and Data Quality
It's never perfect. And so you've got GDPR where you need to make sure that somebody gets forgotten. You've got back fills, you've got mistakes, you've got migrations. All of these things are possible with DT. And there's actually a couple of different uh techniques. Let me walk through them and the trade-offs. So, first of all, I said this before, but I'm going to say it again because it is a very common point of confusion.
I think somebody asks this in our internal channel at least once a week. Streaming tables are tables. You can do DML on them. So if you make a mistake and data needs to get deleted or you need to update some record or you need to insert and do a back fill, you can do insert, update, delete and merge on streaming tables because streaming tables are tables. Um so all of these standard commands work. Uh now I'm going to talk about this in a few slides, but this is not unique to DT, but there are some things you need to think about about delta tables with streaming and changes.
Uh, but I'm going to put a pin in that just a little forward pointer. Um, so this is the I would call it the ad hoc way. And in many cases the ad hoc way is great because it's simple. You understand it. It's familiar. You could even have notebooks and jobs that do this. You know, whatever you need to do. This is an easy way to do it. But sometimes people are really into this idea of CI/CD of proper data engineering. You really want your entire catalog to be specified declaratively.
I don't want there to be manual steps. So, you know, like in data bricks, we run lots of EC2 instances. I would never go into production and kill an ECT2 instance by hand. That would be insane. Everything is version controlled in Terraform. Terraform is the only one who makes changes to production. And so, at some level, like, you know, when you get to the report that the CEO needs every single day and someone's going to get fired if they don't get it, like you want to be a little bit more careful.
And that's where once flows come in. So once flows can be used for onetime backfill. And the nice thing is now it's managed by the pipeline. And so you can see I've got two different flows here. One that is reading the streaming data, the new stuff as it arrives. But I also have this directory of historical data stored in parquet or something else that I want to read only one time and then I never want to ingest it again because you know I know that it's not changing.
I know that it's historical. And so it's super simple to do this. These are both append flows. So they're data that reads from somewhere and then appends that data to the destination that you're writing to. But on the second one, I've added this extra argument once equals true. That tells us that this is a batch job. So it's going to read all that data at once and write it. And it's going to do it one time and then never again unless of course you full refresh.
And so that's actually the magic. That's why it's a good idea if you want to be a little bit more kind of rigorous data engineering to do it this way because now if I do change the query, do a full refresh, it's going to repeat that backfill. So it's going to make sure that this happens automatically. Nobody can fat finger it and forget to do it. So it allows you to make all of the steps of data engineering declarative.
There's also a like really advanced option here. Uh so this is something you know and really this is mostly for like structured streaming experts but sometimes I want to make breaking changes to my stream. I want to change the schema of an aggregation. I want to add a new aggregation. I want to like point to a different Kafka but I don't want to create a separate flow. You have all of the tools available to you. So when we first started declarative pipelines you could only do the most basic streaming things.
But today I'm here to say declarative pipelines is the best way to run structured streaming. It is structured streaming. It has all of the features of structured streaming. Everything you can do in a notebook pretty much you can do in declarative pipelines now. And so here's an example of one of those really advanced things where I want to make a breaking change to this table. So I'm going to actually I was reading from uh oh actually yeah I was reading from table one and now I want to read from table two.
Well the delta streaming source is too smart for this that delta tables have unique ids and you're going to try to start this query and it's going to say that's the wrong table. That's not the one I was reading from before. These offsets don't mean anything. it doesn't want to corrupt your data, so it's going to fail. And so this allows you to make this change, but restarting the stream from scratch. So you'll notice I did a few things here.
I'm going to run reset checkpoint selected. This is a new REST API. We're currently working on adding it into the UI, but there's if you Google this, you'll be able to find the documentation for how to run it by hand today. And then I'm also going to set the starting version. So it's very important to realize when you reset the checkpoint that stream is going to start over from scratch. So structured streaming is no longer protecting you from duplicate data.
It's now your job to make sure that you don't have duplicate data. There's a few ways you can do this. Every different streaming source has different ways to say where it's going to start off. In Delta, it's starting version. Uh in Kafka, it's like uh starting offsets. Uh Kinesis has its own way of doing it. So you can look at the documentation for each source. But you're going to tell this stream when it starts from scratch, where should it begin?
And I picked a pretty common answer here when I said latest. Latest means so by default when you start a stream reading from delta, it starts by reading a snapshot of the table at the beginning. So you get all the historical data and then it begins tailing the transaction log to read new data. This tells it to skip the first step. It's only going to read the new data that arrives in the table after the stream has started because presumably the data is already there.
This is not clearing out the target of this table. So anything anything that was already processed is already there. Cool. Okay. So that was streaming for ingestion. But now we're going to get into more complicated streaming. We're going to talk about aggregations and joins. Here you need to be even more aware of state. So, I want to I I talked about this a little bit, but now that we understand streaming a little bit better, I want to kind of talk about the trade-offs because another super common question is when should I use streaming tables and when should I use materialized views?
47:27 Streaming Aggregations and Joins
And I think here is the right mental model for it. So, first of all, they each have they're both ways of doing incremental computing, but they have different guarantees in how they're going to do that. So, in streaming, we guarantee each new record is only read once and will never be read again, no matter what. In materialized views, we guarantee we're going to give you the correct answer no matter what. So streaming is great because you can get super low latency.
It's only ever reading new new data. Uh but you know, it has limited SQL support. You can't use window functions. There's you can't do quantiles. There's a bunch of things you can't do. And it doesn't support retraction. You cannot delete data from a streaming input. Or if you do, streaming will ignore it or or fail. We'll talk a little bit about that in a moment. But it's only for new data. The right mental model for streaming is I have an appendon table.
New records are being added to it and they're never changing. They're never getting deleted. Materialized views are the exact opposite. Instead of prioritizing performance and latency, they prioritize correctness and expressiveness. Any SQL query you can write can be a materialized view. It just might be expensive to run. So some most things many things will incrementalize and we're you know we're actually working on some ways for you to figure out what does and what doesn't.
But uh you know any query can run but sometimes it's expensive to get the correct answer. And I I'll give an example of that in a moment. So but it supports all of SQL. You don't need to know anything special. And so honestly for most people if you're confused use materialized views. You'll never get it wrong. Especially if you're working with gold tables, you're doing outer joins these kinds of things. You know getting the correct answer is more important.
Streaming is for ingestion. Streaming is for massive data. Streaming is for cases where latency is more important to me. And really the key detail is streaming is when you're willing to deal with that complexity in order to get better performance. So let's talk a little bit about retraction. So first of all, why why is so retraction is this idea that I deleted something in the input? And the question is how you know why is that a hard thing?
Why why wouldn't we just implement this in structured streaming? Well, let me give you an example. Let's say I ran this query select max from numbers. The current answer is 100. There's, you know, a whole bunch of data that we process to get to that. And so, you know, a new record arrives. Well, super easy to do that. Answer still 100. Answer still 100. And then this happens. Somebody deleted the current maximum value.
Okay. Well, what's the new maximum value? Can you tell me? Well, the answer is you cannot because you actually have to look at every single record that was ever processed before. You think if you think about this adversarially, I would just hide the next max in the place you didn't look. And so you have to keep all data forever in order to do this computation and that can be really expensive. And so this is one of the tricks that streaming does to be so cheap and so performant is it just doesn't support this.
It does no retractions and that way it doesn't need any extra storage. It doesn't need to buffer all of this data. So that was that was an example of where streamings are uh streaming is expensive for aggregations or where streaming is cheap for aggregations. But now let's talk about where it's cheap for joins. So you can one type. So a key detail is joins and materialized views. They're just exactly joins in SQL. You do an inner join and outer join.
You're getting exactly the same answer. Joins and streaming are different. There's two different types of them. There's stream snapshot joins and there's stream joins. And you have to reason about their semantics. The first one we're going to talk about is stream snapshot. So the idea here is the snapshot is the dimension table that you're joining with. So, I have like a row of uh a feed of sales coming in from Kafka and I've got a customer table that has their address or something like that.
So, you know, I or I do this join or you know, so I'm pulling up the the cities and uh you know, I the record comes in, I look it up, but then I look at this a little bit more closely and I say that's not how you spell. There's a mistake in it. So, I go and I update that dimension table. Streaming does not go back and update all of these rows that were already processed. only new data that comes in after I make that change to the dimension table will have the new record.
Again, this is a trade-off from correctness and performance. It would be really expensive to go back and update every record that was already processed with this new data. And materialized views will do that. So, you will always get the correct answer. There's no way to know that it was incremental. Streaming does not do that. And often in large cases, this is what you care about. Again, like old data has already been processed. it's it's not worth the cost for me to go back in time and update all those records.
So in many cases, this is what you're looking for, but again, it's kind of a sharp edge. You need to be aware of this. You need to make sure that these are the semantics you want, and if not, you should switch to materialized views. There are also stateful joins, but I I would honestly say this is probably the single most misunderstood feature of uh streaming in general. Stream stream joins are for one very specific use case.
52:34 Handling Data Retractions
They're when I have two facts arriving in within a bounded amount of time for each other and I want to, you know, wait until the other one arrives and, you know, join them and but I and I don't want to have to worry about if one arrives, you know, a minute before or a minute late, I want to make sure I don't miss it. But that's the only thing they're for. They are not for updates. They're not for you know like so if I've got changing dimensions materialized views not stream stream joins I see so many people try to use stream stream joins for changing dimensions and you just don't get the correct answer because it's still append only there is no retraction you cannot do updates but here's an example of where it does work the canonical example is adte I've got impressions and I've got clicks someone someone loads Google and I show a bunch of ads and then you know within a few minutes I expect to get some clicks on them and I want to join that metadata And so what you'll see here, this is an example of a stream stream join.
You need watermarks on both sides. So there's some bound for how long I'm willing to wait for data to arrive. Uh you need a join condition. In this case, it's the click ad ID equals the impression ad ID. So that's what the join is actually happening on. And then you also need a timebound. It says I'm willing to wait this long for the matching record to show up. If you do not put in a time bound, it will buffer every record forever and your state store will blow up.
So a super powerful trick, but very rarely the thing you're actually looking for. And yeah, so you will all data forever. Be careful not to do that. Um, okay. So we've talked a lot about streaming. We talked about how it doesn't support retraction, but sometimes changes happen in Delta. How are we going to handle that? So you know as we said structured streaming is assuming that inputs are append only and for Kafka that's totally fine.
You can't really delete data from Kafka. It just gets retentioned out over you know at whatever period you say. But Delta supports update delete and merge as we said before. And since streaming doesn't know how to handle this when it sees one of these changes in a table that you're streaming from it's going to throw an exception. And this is I would say the most common exception pasted on our internal channel is what do I do about this?
Um and so the question is if I need to do this I I you know I had one of those one-off cases. There was like some data leaked or there was a mistake and I want to correct it. I need to fix it. How can I do this in a streaming system? There's three choices and it really which one you pick depends on your particular use case. Let's go through them. The easiest one option number one is don't do changes. And if you're picking this one, I encourage you to set this table property because I have had several customers who didn't do this and then someone doesn't know what's going on.
They run an update now that all their pipelines are broken and it's a it's an escalation. So set this table property and Delta will protect that table. It will only allow you to append to it. You can never make updates to it. You'll never have problems streaming from it downstream. Everything is good. You can always clear it if you need to. But I think this is a great safety net. We actually created this for that original customer that we created Delta for because they were very rigorous about not losing data.
So set that on any table you're streaming from. You'll never have a problem. So but this is the real world. Sometimes you have to make changes. So what else can we do? Another option is you're going to handle those changes manually. So in this case you're telling the streaming engine, it's okay. I understand that you don't understand how to do retraction. Why don't I take care of it for you? So the option here is called skip change commits and basically what it does is it tells streaming when it runs into a commit in the delta tables you know some atomic operation that was done on it outside of the pipeline instead of failing and saying I can't process this because you know streaming doesn't want to give you the wrong answer you're saying it's okay just ignore those and this might actually be the right thing to do in many cases people are using streaming for the common case in fact this is how we often use it internally at data bricks for a lot of our telem telemetry pipelines.
The new data is streamed through. Corrections are relatively rare and now you can do them manually. So you can just do uh delete, update, merge on that table, but you have to realize that's not automatically getting propagated downstream anymore. It's on you to either say that's okay. Maybe I'm doing an aggregation. Maybe I'm filtering out sensitive data, so I don't care that it's not getting deleted from downstream.
It's fine. Or maybe I really do. And then you need to run delete delete delete on every table so that you make sure that it happens. So basically in this case you're saying I'm going to handle it manually. I'm going to take care of it. Okay. And then option three. This is the most complicated option but is super powerful. So I wanted to talk about it a little bit. In addition to reading a delta table as a stream where basically you're getting that guarantee that you're always going to get exactly the same answer as if you ran a query on that table by hand.
Reading the change feed does this really cool trick. It takes a table that has changes and it turns that into an appendon feed of changes. So now you're getting this ever growing table, but rather than being the actual table, it's a list of everything that happened to the table. And this lets you write custom logic that decides how am I going to handle each different type of operation that could occur. And so you can see here I I only wrote a little bit of it out because I it's actually a pretty complicated thing to do this, you know, end to end.
But here I'm actually looking at that change type record from delta. So you know you can imagine like if I was calculating a running sum and I wanted to do it using streaming and I wanted to support retraction. This is basically the kind of logic you'd be writing out. If there's a new record well of course I just use that value. If there's a deleted record well I want to delete a value that was previously considered.
If there's an updated value we actually model that as a delete followed by an insert. That's the pre-image and the post image. It's the row before the change and the row after the change. And so you can write this out and then you can feed that into an aggregation and you've now turned something that was changes into an append only stream that can have custom logic. So definitely the most advanced version of this but I think you know one of those three.
So the three options are disallow changes entirely, skip the changes or handle the changes manually. And today you don't get any warnings. But the next thing I want to add to that ID for data engineering is if you're not doing one of these, it's going to have a big red box and tell you pick which one you're going to do so you don't have that outage later. Okay, so that's streaming for ingestion. Now let's talk about another use case with change data capture.
This is one of my favorite features. I actually think this is one of the most popular features of declarative pipelines because change data capture is incredibly common. So we're going to do a case study first because this looks so simple I have to explain why it's hard. Um the problem is super simple. I have a feed of changes coming from some other system. You know I might be running debzium. I might be running golden gate.
59:23 AutoCDC and Advanced Features
I might be getting it from some some you know system upstream that I don't even understand. But it's really simple. There's a primary key. You can see that is the ID column. There's a timestamp, a log sequence number, some way for us to know when this change actually happened. And then there's the actual data, the rest of the table. And the goal here of CDC is to take the latest value for every key. So I just want to, you know, scan through that.
And you can think of this as like an upsert, but it's a smart upsert. And that's where things get complicated. It sounds really simple to do this. You're like, well, that's just a group by. But the problem is in streaming, data can always arrive late. It can arrive out of order. And that actually turns us into a much more complicated problem. So if you go into Google and you say, how do I do change data capture with Spark?
You're probably going to get something a lot like this. Uh, and it's pretty simple. You know, I'm starting a stream. uh for each micro batch of that stream I'm running merge and I'm just taking the records and merging them into this table. Can anyone guess what's wrong with this code? It does not handle multiple updates to the same key. So if in a single microbatch you have two updates for the same key and oftent times microbatch boundaries are arbitrary.
It's just where the system happened to put them based on how the data was arriving. U so this can this can happen pretty easily. You're going to get an error. merge is gonna blow up and say, "I can't do this because it's ambiguous. I don't know which record to pick." And so you're gonna get an error. You're gonna have to fix it. So, um, we're gonna modify our code a little bit and we're basically going to add an extra aggregation to every single microbatch.
So, we're going to group by that primary key that we care about. We're going to use this aggregate function max by where we're going to, you know, basically take the record that has the largest time stamp. We'll take all of the columns. We'll pack it into a strruct and then we'll unpack it back out. And so you can see the transformation. It's super simple. We're of course going to pick the one that is at 1201. And so we're good to go.
So we'll add that to the beginning of our for each batch function. And now we're correct. And so it's a little bit more complicated. We're now at 18 lines of code, but it is unfortunately still incorrect. So and the problem with this one is this one's not actually even going to give you an error. You're just going to have stale data in your table forever. I have seen so many people implement for each batch with this bug in it and I think they never figure out that things are broken.
So the problem here is out of order updates across batches. If you notice the time is going down but the earlier record came first and then the later record came second and that merge command doesn't know anything about this. So it's just going to happily overwrite the new data with the old data. And now your table is possibly stale forever and someone downstream is going to be upset with you. And so this out of orderness causes a bunch of problems.
And so to fix it, it's we're getting a little bit more complicated. We're gonna have to write out this logic where we're actually going to remember for each record what was the time stamp for this record originally. And so you can see we're doing this. If the record is newer, then remember the newer time stamp. If the new record is newer, then update this column. You have to write it out for every single column in your table.
So now it's getting a little bit ownorous to write this thing. and you're probably doing some meta programming, some string concatenation to create this merge statement. Um, and so we can add that in. And you know, now we're at over 22 lines of code. So, this is getting pretty complicated and it's still not finished. There's another feature. This one sounds pretty simple. We're going to add, we need to handle deletes.
Usually, the way that deletes happen at a change feed is there's a special flag that says this row is being deleted. So, here we have the is delete flag set to true. And so handling that is simple in merge. But I have bad news for you. While this looks simple, it actually introduced yet another race condition into the code. So we're at 23 lines of code with a new race condition. Imagine this case where now an update arrives late after a delete.
There's no longer a timestamp in the table to protect us from this. So I think this is a brand new record that I've never seen before because I deleted it. And now we have the worst thing, a zombie in our database. Uh, this stale record is going to stick around possibly forever. Again, confusing everybody downstream, getting me yelled at by my manager. And so handling this is getting pretty complicated because we're going to need to remember that there was a row here before, but it's not there anymore.
We'll call this a tombstone. So we'll implement this using a technique called soft deletes. Instead of deleting the record for real, you're just going to record this was deleted at this time. Now, I don't want to confuse everybody downstream with all these tombstones. They don't care about it. The record was deleted. So, I'm going to have to create a view that filters out the tombstones. And I'm going to have to redirect everybody to read from that view instead.
And of course, I don't want these tombstones to accumulate forever because that would be very expensive. And so, we'll have to build a job that deletes these tombstones over time. And so coming back to our example, we've added a couple of lines of code. We've created this view. We've created this cleanup job. We're at 24 lines of code. One view, one cleanup job. There's got to be an easier way than this. And that is why we created AutoC.
It takes all of that logic that we just talked about and it makes it declarative. So instead of spelling out all of the procedures that you need to do to handle every possible race condition, you just say what you want to have happen and the system figures it out. This is another type of flow in the system, but it's a very specialized flow for this one type of use case that is so common that we built it directly into the system.
So with five lines of code, all I have to say is, you know, where I'm writing to, where the changes are coming from. This is any streaming source. It could be Kafka, it could be files, it could be a delta table, it could be a change feed from a delta table. Um, you tell it what the primary key is. The primary key can be composit. So you could put multiple columns here if you want. You put a sequence by, which is, you know, how I'm going to think about ordering.
What is that timestamp column? Again, this can be composite. If you've got like a timestamp and a log sequence number that uh breaks ties within those, all you need to do is create a strct and put those together. The first uh the first column in the strct will be considered first. And if there's ties in the first column, we'll use the second column to break them. Uh and so and then apply as delete if you want to use that feature.
So five lines of code, every race condition handled automatically. Pretty cool. So that's the simple case, but it turns out the all there's like a we interviewed like I think a hundred customers asking them about every different type of change feed they have. And one thing that a lot of databases will do is they'll save space because they won't they don't want to output every column every time. The rows, you know, maybe have a thousand columns in them.
And so they'll start outputting only the columns that change. And now the system needs to be a little bit smarter. It actually needs to collapse these down. So in this example, you know, one record had the name, the next record had the city. I want to combine them together into one record. And how do we do that? Well, it's as easy as adding ignore all updates. I won't bore you with the details of how to implement this, but basically instead of keeping a single time stamp, you start keeping a vector clock of time stamps inside of the table.
Instead of remembering when a row changes, remembers when each column changes. And you can imagine that merge statement is getting more and more complicated. Um so you know still five lines of code handled. Another really common thing is you want to keep history and actually I would say this is one of the most powerful parts of apply changes into um I you know I don't want to just update those rows in place. I'm in a regulated industry.
I need to understand exactly how the data was not only today but also in the past. So I can recreate analyses that were done previously and I can figure out exactly the providence of decisions we made or whatever. Doing that with apply with autocd you'll notice I'm almost saying apply changes into that's the previous name of this. Um but it's again no no changes all your old syntax continues to work. I would update it so you're not conf the docs but um all you do is add store as sedd2 and this is going to create two new columns in your table start at and end at.
And so for every record you'll have the moment that row was first created with those values and then how long it existed with those values. And now when there's an update instead of updating in place we'll create a new row that has the new values. And that way you can look at this thing and get historical data out of it. And I would love to talk about how sedd2 works but there is not enough time. It's super complicated and the real answer here is you could build autocdc yourself.
Uh and like really everything in declarative pipelines is just a spark program. We just set and wrote a whole bunch of Scola. Um but the key trick here is the implementation of autocd is over 2,000 lines of code. And I actually think more important is it has over 10,000 lines of tests. And that's the like that's the hard part. I think a lot of times when people are building these one-off data engineering things in notebooks, you're missing that rigor.
You don't have randomized testing making sure that you've got all the race conditions exactly right. And so that's why I think it's so powerful when there is a pattern that is taken care of by the system to let it handle it for you because now there's like 30 engineers at data bricks whose job it is to make sure that thing is correct. Okay, another really cool feature of declarative pipelines is expectations. So expectations are a way to ensure correctness.
1:08:58 Pipeline Expectations
You can think of them a lot like constraints in a delta table. So delta, you know, has always had this ability where you could create a constraint. It's just a boolean expression that is evaluated on each row. But with a constraint, you have very little flexibility. A constraint is like the transaction manager is enforcing this thing and if you try to insert even a single row that doesn't match that constraint, the entire transaction aborts.
And in big data, if you're aborting anytime something goes wrong, you might actually not get anything done. And so expectations allow you to tune this and actually have a policy for how we're going to handle uh violations to the these constraints that you put on it. So I gave both the SQL syntax and the Python syntax. Um but the policies here are pretty cool because in some cases you actually don't want to do anything.
You just want to know how many rows were bad and then you want to have like an alert on it. If it's 5% everything's good. If it's 50% up, like something's wrong. Figure out what's going on. And so track or allow is pretty simple. That's if you don't give any policy. By default, what an expectation is going to do is it's just going to give you that data quality indicator inside of the UI. Another option is to drop. So you can think about this like putting a filter on the table, but it's a filter with an insurance policy.
Because a a key problem that I have seen over and over in people's pipelines is they put a filter like you know filter out where date is null but then they start dropping 90% of their data and like figuring out where 90% of the data was dropped is quite difficult especially if you have one of these complicated pipelines. So drop expectations are more powerful because not only do we filter that data out so it doesn't affect people downstream but we record exactly how many rows that happened to.
And then finally, we have something very similar to fail expectations. But the key difference here is since it's inside of a declarative pipeline, we can actually track the provenence of the row that caused the expectation to fail. And we can tell you this was the input row, this was the output row, this is why you have a problem. Expectations are super powerful because you can put them on tables, but you can also put them on materialized views, you can put them on apply changes into tables.
And without going into too much detail, imagine implementing something like drop expectations on apply changes into where a new record comes in and corrects something. So now it is valid. So again, you can't actually drop them. You have to do this soft delete trick and hide them out. So the implementation ends up being quite complicated. Uh but I think it's actually a very powerful tool. Um and there's a bunch of kind of subtle ways you can use expectations that are not obvious.
You can use them of course to do this like is date null or whatever you know to protect from bad data but there are a couple of other cases I think are pretty cute. So a lot a question I get a lot is like what about aggregate expectations? Well those are supported with materialized views. So if I were to for example I want to enforce a primary key constraint. So all I do is create a materialized view that is incrementally computing how many times we see each key.
So that's efficient for us to maintain. And now that expectation is going to cause the pipeline to blow up anytime we see a case. And this because it's a materialized view will work with updates. It'll work with deletes. It'll work with inserts all automatically and incrementally. It's pretty powerful. Another one is joins. This is another kind of classic example that I see in data pipelines where people have a join and then there's some data missing from that dimension and it causes a ton of data to get dropped.
And figuring out which join caused the problem to occur can be really difficult for people. And so here's a trick where instead of doing an inner join, I'm going to switch it to be an outer join. So now even when something doesn't line up, we're still going to emit a row and it's just going to have null for all of those missing columns. But I don't want to confuse my downstream people. They're going to say, why why are you producing this like partially valid data?
So I'm going to put a drop expectation on it. And now you're getting that really cool trick of the system will tell you if 50% of your data is being filtered out by this join, you'll know about it instead of instead of having no observability into that problem. Okay, just a few more topics. Um, now that we've got this ability to write pipelines as source code and everything is declarative, I want to kind of take it to the next step.
I want everything to be declarative including uh the deployment of the jobs, the deployment of the pipelines and that's where dabs comes in. So dabs is super powerful because it lets you kind of do this what I was talking about before like in data bricks nobody touches production that would be crazy and so dabs let you do the kind of same thing with your data lake. Um basically you know you can use dabs to automate and version control the creation of all of the resources inside of your workspace.
1:13:32 DABs and Meta-programming
And so in one example here, I'm actually using it to not only control just one workspace, but control many workspaces. My dev workspace, my staging workspace, my prod workspace. Make sure they always stay in sync with each other. Make sure I don't like forget to do something in staging before I test it, you know, test something in staging before I deploy it to prod. You can automate all of those things. And so the really cool thing about DABS is it's exactly the same API that you're using when you use the rest API inside of data bricks.
Um, but you can override the parameters for different environments. So you know in this case I am changing the catalog that we're writing to um or the the schema that we're writing to. In dev I publish to dev and prod I publish to prod and then all of the pipelines kind of automatically inherit that setting. Um there's a couple of other patterns. This one I think is actually really powerful. Oftent times you do not want your staging and development pipelines to be super expensive to run and so you want to run them on smaller or sample data.
And so there's this pattern that I recommend to people where you separate the directories for sources and transformations. Sources are the inputs to the pipeline. Something that reads an external input from the system. So I'm reading from some table, some files, whatever it is. You kind of make that a separate uh thing so that you can have different versions depending on what environment you're working in. And then transformations are the real meat of your pipeline.
They're the thing the act the thing that's actually doing work. You want those to be the same everywhere. And then of course you want to use uh expectations for validations. So here's an example of what this actually looks like. So you can see I'm reading from some table called sales that my co-workers have created for me. And uh you know I what I'm going to do is I'm going to create these two different directories dev and prod.
And for every source I'm going to create a different file. And I'm going to create parallel versions of every file. So in prod I'm just going to create a view. So this is free. You know there's no extra cost. It's just a layer of indirection. I'm going to read from that table upstream. I'm going to read the whole table because it's prod and I want to process all the data. But in dev, it's way too slow. I need to iterate really quickly.
That table is huge. It's got 12 years of data in it. And so instead uh in dev, I'm only going to read the last day worth of data. And so now the transformation is going to automatically get stitched together by the declarative pipeline compiler. In dev, it's going to read from one view and prod's going to read from the other view. It doesn't need to know which environment it's in. It just magically gets the correct data set.
And now I've got fast development and correct production. And there's a bunch of different ways you can create this test data. I showed an example where we did a subset with a filter. But you could of course also hardcode it if there's like a pathological input that you want to make sure you test with. Uh if I want to read from a JSON file where I've hardcoded a bunch of values or if I even want to randomly generate data to test what my pipeline is going to do with large amounts of synthetic data.
So, I think these are all kind of cool techniques that you can use here. And of course, sources and transformations can all be automated with DABs. You can see in this example, I'm using a really cool new feature that we just added called Globs, where you can read an entire directory. So, the entire dev directory of sources, the entire prod directory of sources uh will let you take care of that. Uh, metaroming in Python.
So, this is super powerful. This is I actually I would say most of our largest customers with the largest pipelines are using this trick. Um the idea is if I have 100,000 tables that I want to ingest, I don't want to cut and copy that because then if I need to make a change, I need to make it in a 100 different places. And so what metaroming lets you do is you're writing an imperative program that produces the graph.
And so in this case, I've got a for loop that is automating creating a report for every single region. And where you get this data from is kind of up to you. Some people store it in a JSON file. Some people store it in a table. Uh you know, some people store it in some schema registry outside of the system. Um there is a a trick here. You'll notice that I put the at DLT table in a function rather than calling it directly in the for loop.
This is like really weird Python details, but the way variable capture works in Python, if you put it directly in the for loop, you're not actually capturing the value of the variable at that moment in the iteration of the loop. You're capturing the container. And so when you get to the point where DT's code runs, everyone has the final value of the loop. Uh so just make sure it is called out in the docs, but just make sure if you're ever confused that you're following this pattern.
But so this is super cool and the story that I hear over and over again with this pattern is there's a small engineering team. They have hundreds of data analysts. They can't keep up with all of their requests. They want to make sure that they're enforcing the standards of the business that tables are created with the right schema and metadata and all these other things. And so they'll create these metadata frameworks.
And now these less technical users can ingest data, transform data just by editing these JSON files, just by inserting a row into maybe an Excel spreadsheet or something. And that's super powerful. Okay, one final topic. Sometimes there's stuff that doesn't fit into DLT. Uh, and you need these declarative escape hatches. And this is actually by design. I think this is the right way to think about declarative programming.
1:18:54 Procedural Escape Hatches
As I mentioned before, declarative programming is not as powerful as imperative programming. It is not a touring programming language. You cannot do arbitrary computation in it. And a lot of the power, a lot of the things that we're able to do come from the fact that we understand what's going on and it's not arbitrarily complicated. But that also means that sometimes we're missing stuff. And I think even as t goes to infinity and you know if we've like polished every possible edge of declarative pipelines, I think it's going to handle 80% of your ETL, 80 or 90% of your ETL.
But there's going to be that 10 to 20% that is custom where like you have some weird thing about your business that nobody else has and it's worth it to you to optimize it. And so it's important to understand what your escape hatches are. How can I still do these complex things? Well, the first and easiest answer is we talked about this at the beginning, but LakeFlow jobs can run everything. You can use it to run pipelines, but you can also use it to run notebooks, jars, wheels, dashboards, DBD projects, snowflake queries, anything you want to run.
And so a really common pattern here is you'll do 90% of the work in a DT pipeline and then you'll use a multitask job that runs some arbitrary logic after that or before it to prepare the data. And so absolutely I I had a couple of executives who like they heard the elevator pitch and then they banned using anything other than declarative pipelines. That's not the right way to do this. Like I you know and I'm very selfish here.
I would love for you to use declarative pipelines, but sometimes it's not the right tool for the right job and you should consider using this as well. There's a couple of other tricks too where you can actually stay within the declarative framework but wrap small parts of procedural code. Uh for example, if I want to integrate with external data sources, you don't want to do this in the main body of your DT pipeline because you shouldn't be doing anything that has side effects there.
You should only be creating the graph there because we reserve the right to run your code possibly multiple times with retries and other things. But data sources give you this nice little wrapper where you can create a data source that integrates with some external system. You can let streaming manage the state of that data source for you. It's secure and isolated even when you're using shared computer serverless. And this allows you to do incremental ingestion.
You should go and Google for this GitHub data source. It's like super powerful. will actually like pull GitHub for new pull requests using the like last time stamp that we saw to get the new ones and it stores it all inside of there and streaming manages all that state for you. And the cool thing is all you need to do is create this Python data source. You can use this both for reading and for writing. You can use it both for streaming and for batch.
This is new in Spark 4. 0. But this works seamlessly inside of a declarative pipeline because you've created this little wrapper that is the data source and then the rest of the pipeline is still this declarative this table should exist. I should be reading from this streaming source. Another one is for each batch. So for each batch lets you wrap procedural code that operates on new data. And so it's just a slightly different syntax than in structured streaming, but it's exactly the same idea.
You just create one of these functions. You get a batch data frame which has the new data that has arrived since you last processed and you get a batch ID which just lets you track whether or not you've processed this before. But there are a bunch of sharp edges here. I have seen so many bad for each batch implementations and in fact that's why I gave that whole talk about auto CDC because it's very easy to get it wrong.
You do not have any of the protections of exactly one semantics when you're doing for each batch. we guarantee we're going to call that function at least once and so if it fails in the middle we're going to call it again and you might get duplicate data. It's up to you to figure out how you're going to handle possibly duplicate data. Uh another kind of really common thing that I see is people are like well streaming told me I couldn't do this aggregation but I can do it in for each batch.
Well you're only running that aggregation on that chunk of data. It's not seeing any of the data from previous executions. So maybe that's what you want but maybe that's actually the wrong answer. So it is it is working but it might not be the correct answer. Make sure you understand those semantics before using this escape hatch. And finally we have transform with state. I talked about this today in the Spark keynote.
I think this is really cool. We used to have probably the my least favorite API that I created my entire time working on Spark. Flat map groups with state. It was complicated. It was slow. It wasn't powerful. Transform with state is so much better. It lets you basically you can group by something and we will give you every record in that group. You have full access to the state store. So you can store individual values.
You have like a key value store per group that you can use. You can maintain lists if you want to kind of keep long arrays of things and you can do that efficiently. Um and then you can output whatever results you want and you have access to timers and TTL so you can do expiry if you want to do things like session windows. So if you've got really complicated stateful logic, wrap it in one of these transform with state functions and you can do pretty much arbitrarily complicated things here.
Okay. And with that, I think we have a few minutes for questions. Thank you so much for bearing with me.
Learn more about the Databricks Data and AI platform.
The information provided herein is for general informational purposes only and may not reflect the most current product capabilities or configurations.