<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adam Bellemare on Medium]]></title>
        <description><![CDATA[Stories by Adam Bellemare on Medium]]></description>
        <link>https://medium.com/@adam.bellemare?source=rss-d53537b5589d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XhFWtqklX1NQTe7kE824cw.jpeg</url>
            <title>Stories by Adam Bellemare on Medium</title>
            <link>https://medium.com/@adam.bellemare?source=rss-d53537b5589d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:37:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adam.bellemare/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Preventing and Fixing Bad Data in Event Streams — Part 2]]></title>
            <link>https://medium.com/confluent/preventing-and-fixing-bad-data-in-event-streams-part-2-526e459c7c6f?source=rss-d53537b5589d------2</link>
            <guid isPermaLink="false">https://medium.com/p/526e459c7c6f</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Adam Bellemare]]></dc:creator>
            <pubDate>Wed, 22 May 2024 18:35:10 GMT</pubDate>
            <atom:updated>2024-07-02T18:28:04.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preventing and Fixing Bad Data in Event Streams — Part 2</h3><p>Alright, I’m back. Time for part 2.</p><p><a href="https://medium.com/@adam.bellemare/preventing-and-fixing-bad-data-in-event-streams-part-1-27bf2a99b48e">In the first part</a>, I covered how we handle bad data in batch processing. In particular, cutting out the bad data, replacing it, and running it again. But this strategy doesn’t work for immutable event streams as they are, well, immutable. You can’t cut out and replace bad data like you would in batch processed data sets.</p><p>Thus, instead of repairing after the fact, the first technique we looked at is <em>preventing bad data </em>from getting into your system in the first place. Use schemas, tests, and data quality constraints to ensure your systems produce well-defined data in the first place. To be fair, this strategy would also save you a lot of headaches and problems in batch processing.</p><p>Prevention solves a <em>lot</em> of problems. But there’s still a possibility that you’ll end up creating some bad data, such as a typo in a text string or an incorrect sum in an integer. This is where our next layer of defense in the form of e<em>vent design </em>comes in.</p><p><strong>Event design</strong> plays a big role in your ability to fix bad data in your event streams. And much like using schemas and proper testing, this is something you’ll need to think about and plan for during the design of your application. Well-designed events significantly ease not only bad data remediation issues, but also related concerns like compliance with <a href="https://gdpr-info.eu/">GDPR</a> and <a href="https://oag.ca.gov/privacy/ccpa">CCPA</a>.</p><p>And finally, we’ll look at what happens when all other lights go out — you’ve wrecked your stream with bad data and it’s unavoidably contaminated. Then what? <strong>Rewind, Rebuild, and Retry</strong>.</p><p>But to start we’ll look at event design<strong>,</strong> as it will give you a much better idea of how to avoid shooting yourself in the foot from the get-go.</p><h3>Fixing bad data through event design</h3><p>Event design heavily influences the impact of bad data and your options for repairing it. First, let’s look at <strong>State (or Fact)</strong> events, in contrast to<strong> Delta (or Action)</strong> events.</p><p><strong>State</strong> events contain the entire statement of fact for a given entity (e.g., Order, Product, Customer, Shipment). Think of state events exactly like you would think about rows of a table in a relational database — each presents an entire accounting of information, along with a schema, well-defined types, and defaults (not shown in the picture for brevity’s sake).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxO2gsA72MapMfjs" /><figcaption>State shows the entire state. Delta shows the change.</figcaption></figure><p>State events enable<strong> </strong><a href="https://martinfowler.com/articles/201701-event-driven.html#Event-carriedStateTransfer">event-carried state transfer</a> (ECST), which lets you easily build and share state across services. Consumers can <em>materialize </em>the state into their own services, databases, and data sets, depending on their own needs and use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQv04SM3XnLKU0YA_NI75g.png" /><figcaption>Materializing an event stream made of State events into a table.</figcaption></figure><p>Materializing is pretty straightforward. The consumer service reads an event (1) and then upserts it into its own database (2), and you repeat the process (3 and 4) for each new event. Every time you read an event, you have the option to apply business logic, react to the contents, and otherwise drive business logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiR5fG_4KC8ll5oOnO5fQA.png" /></figure><p>Updating the data associated with a Key “A” (5) results in a new event. That event is then consumed and upserted (6) into the downstream consumer data set, allowing the consumer to react accordingly. Note that your consumer is not obligated to store any data that it doesn’t require — it can simply discard unused fields and values.</p><p>Deltas, on the other hand, describe a change or an action. In the case of the Order, they describe <strong>item_added</strong>, and <strong>order_checkout</strong>, though reasonably you should expect many more deltas, particularly as there are many different ways to create, modify, add, remove, and change an entity.</p><p>Though <a href="https://developer.confluent.io/courses/event-design/fact-vs-delta-events/">I can (and do) go on and on about the tradeoffs of these two event design patterns</a>, the important thing for this post is that you understand the <em>difference</em> between Delta and State events. Why? Because <em>only</em> State events benefit from <a href="https://docs.confluent.io/kafka/design/log_compaction.html">topic compaction</a>, which is critical for deleting bad, old, private, and/or sensitive data.</p><p><strong>Compaction</strong> is a process in Apache Kafka that retains the latest value for each record key (e.g., Key = “A”, as above) and deletes older versions of that data with the same record key. Compaction <a href="https://docs.confluent.io/kafka/design/log_compaction.html#compaction-enables-deletes">enables the complete deletion of records via tombstones</a> from the topic itself — all records of the <em>same key</em> that come <em>before</em> the tombstone will be deleted during compaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*gxO80mBDPBz9GtOi" /><figcaption>Compacting an Event Stream (an asynchronous process) — <a href="https://docs.confluent.io/kafka/design/log_compaction.html#view-of-compaction">Source</a></figcaption></figure><p>Aside from enabling deletion via compaction, tombstones also indicate to registered consumers that the data for that key has been deleted and they should act accordingly. For example, they should delete the associated data from their own internal state store, update any business operations affected by the deletion, and emit any associated events to other services.</p><p>Compaction contributes to the eventual correctness of your data, though your consumers will still need to deal with any incorrect side-effects from earlier incorrect data. However, this remains identical as if you were writing and reading to a shared database — any decisions made off the incorrect data, either through a stream or by querying a table, must still be accounted for (and reversed if necessary). The eventual correction only prevents future mistakes.</p><h3>State Events — Fix It Once, Fix It Right</h3><p>It’s <em>really easy</em> to fix bad state data. Just correct it at the source (e.g., the application that created the data), and the state event will propagate to all registered downstream consumers. Compaction will eventually clean up the bad data, though you can force compaction too if you cannot wait (perhaps due to security reasons).</p><p>You can fiddle around with compaction settings to better suit your needs, such as compacting ASAP or only compacting data older than 30 days (<a href="https://docs.confluent.io/platform/current/installation/configuration/topic-configs.html#min-compaction-lag-ms">min.compaction.lag.ms</a>= 2592000000). Note that active Kafka segments <a href="https://docs.confluent.io/kafka/design/log_compaction.html#:~:text=If%20not%20set%2C%20all%20log,the%20minimum%20compaction%20time%20lag.">can’t be compacted immediately</a>, the segment must first be closed.</p><p><strong>I like state events.</strong> They’re easy to use and map to database concepts that the vast majority of developers are already familiar with. Consumers can also <em>infer</em> the deltas of what has changed from the last event (n-1) by comparing it to their current state (n). And even more, they can compare it to the state before that (n-2), before that (n-3), and so forth (n-x), so long as you’re willing to keep and store that data in your microservice’s state store.</p><p>“But wait, Adam!” <br>I have heard (many) times before. <br>“Shouldn’t we store as little data as possible so that we don’t waste space?”</p><p>Eh, Kinda.</p><p>Yes, you should be careful with how much data you move around and store, but only after a certain point. But this <a href="https://jcmit.net/diskprice.htm">isn’t the 1980s, and you’re not paying $339.8 per MB</a> for disk. You’re far more likely to be paying <a href="https://aws.amazon.com/ebs/pricing/">$0.08/GB-month</a> for AWS EBS gp3, or you’re paying <a href="https://aws.amazon.com/s3/pricing/">$0.023/GB-month for AWS S3</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*46KBwJvS7uDBpbLM" /><figcaption>An example of a faulty mental model of storage pricing held by some developers</figcaption></figure><p>State is <strong>cheap. </strong>Network is <strong>cheap</strong>.<strong> </strong>Be careful about cross-AZ costs, which <a href="https://www.lastweekinaws.com/blog/awss-anti-competitive-move-hidden-in-plain-sight/">some writers have identified as anti-competitive</a>, but by and large you don’t have to worry excessively about replicating data via State events.</p><p>Maintaining per-microservice state is very cheap these days thanks to cloud storage services. And since you only need to keep the state your microservices or jobs care about, you can trim the per-consumer replication to a smaller subset in most cases. I’ll <em>probably </em>write another blog about the expenses of premature optimization, but just keep in mind that state events provide you with a ton of flexibility and let you keep complexity to a minimum. Embrace today’s cheap compute primitives, and focus on building useful applications and data products instead of trying to slash 10% of an event’s size (heck — just use compression if you haven’t already).</p><p>But now that I’ve ranted about state events, how do they help us fix the bad data? Let’s take a look at a few simple examples, one using a database source, one with a topic source, and one with an FTP source.</p><h4><strong>State Events and Fixing at the Source</strong></h4><p><a href="https://kafka.apache.org/documentation/#connect">Kafka Connect</a> is the most common way to bootstrap events from a database. Updates made to a registered database’s table rows (Create, Update, Delete) are emitted to a Kafka topic as discrete state events.</p><p>You can, for example, connect to a MySQL, PostgreSQL, MongoDB, or Oracle database using <a href="https://debezium.io/documentation/reference/2.6/connectors/index.html">Debezium (a change-data capture connector)</a>. Change-data events are <strong>state-type</strong> events, and feature both <strong>before</strong> and <strong>after</strong> fields indicating the before state and after state due to the modification. <a href="https://debezium.io/documentation/reference/2.6/connectors/mysql.html#mysql-update-events">You can find out more in the official documentation</a>, and there are plenty of <a href="https://www.confluent.io/blog/how-change-data-capture-works-patterns-solutions-implementation/">other articles</a> written on CDC usage on the web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CTTu_LxOu4_QoFvh" /><figcaption>Fix the bad data at the database source and propagate it to the compacted state topic</figcaption></figure><p>To fix the bad data in your Kafka Connect powered topic, simply<strong> fix the data in your source database (1)</strong>. The change-data connector (CDC, 2a) takes the data from the database log, packages it into events, and publishes it to the compacted output topic. By default, the schema of your state type maps directly to your table source — so be careful if you’re going to go about migrating your tables.</p><p>Note that this process is <strong><em>exactly the same as what you would do for batch-based ETL</em></strong>. Fix the bad data at source, rerun the batch import job, then upsert/merge the fixes into the landing table data set. This is simply the stream-based equivalent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d3ffL_5wyfQ52ZBi" /><figcaption>Fix the bad data in the compacted source topic and propagate it to the downstream compacted state topic</figcaption></figure><p>Similarly, for example, a Kafka Streams application (2) can rely on compacted state topics (1) as its input, knowing that it’ll always get the eventually correct state event for a given record. Any events that it might publish (3) will also be corrected for its own downstream consumers.</p><p>If the service itself receives bad data (say a bad schema evolution, or even corrupted data), it can log the event as an error, divert it to a dead-letter queue (DLQ), and continue processing the other data (<a href="https://medium.com/@adam.bellemare/preventing-and-fixing-bad-data-in-event-streams-part-1-27bf2a99b48e">Note that we talked about dead-letter queues and validation back in part 1</a>).</p><p>Lastly, consider an FTP directory where business partners (AKA the ones who give us money to advertise/do work for them) drop documents containing information about their business. Let’s say they’re dropping in information about their total product inventory, so that we can display the current stock to the customer (Yes, sometimes this is as close to event streaming as a partner is willing or able to get).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ULr1LTqQAsXycDlo" /><figcaption>Bad data dropped into an FTP directory by a careless business partner</figcaption></figure><p>We’re not going to run a full-time streaming job just idling away waiting for updates to this directory. Instead, when we detect a file landing in the bucket, we can kick off a batch-based job (AWS Lambda?), parse the data out of the .xml file, and convert it into events keyed on the <strong>productId</strong> representing the current inventory state.</p><p>If our partner passes us <em>bad data</em>, we’re not going to be able to parse it correctly with our current logic. We can, of course, ask them nicely to resend the correct data(1), but we might also take the opportunity to investigate what the error is, to see if it’s a problem with our parser(2), and not their formatting. Some cases, such as if the partner sends a completely corrupted file, require it to be resent. In other cases, they may simply leave it to us data engineers to fix it up on our own.</p><p>So we identify the errors, add code updates, and new test cases, and reprocess the data to ensure that the compacted output (3) is eventually accurate. It doesn’t matter if we publish duplicate events since they’re effectively benign (idempotent), and won’t cause any changes to the consumer’s state.</p><p>That’s enough for state events. By now you should have a good idea how they work. I like state events. They’re powerful. They’re easy to fix. You can compact them. They map nicely to database tables. You can store only what you need. You can infer the deltas from any point in time so long as you’ve stored them.</p><p>But what about deltas, where the event doesn’t contain state, but rather describes some sort of action or transition? Buckle up.</p><h3>Can I fix bad data for delta-style events?</h3><p>“Now,” you might ask, “What about if I write some bad data into a delta-style event? Am I just straight out of luck?” Not quite. But the reality is that it’s <strong><em>a lot</em></strong> harder (like, a lot a lot) to clean up delta-style events than it is state-style events. Why?</p><p>The major obstacle to fixing deltas (and any other non-state event, like commands) is that <strong><em>you can’t compact them — no updates, no deletions. </em></strong>Every single delta is essential for ensuring correctness, as each new delta is in relation to the previous delta. A bad<em> </em>delta represents a change into a bad state. So what do you do when you get yourself into a bad state? You really have two strategies left:</p><ol><li><strong>Undo </strong>the bad deltas with new deltas. This is a <strong>build-forward</strong> technique, where we simply add new data to undo the old data. (<strong>WARNING</strong>: This is very hard to accomplish in practice).</li><li><strong>Rewind, rebuild, and retry </strong>the topic by filtering out the bad data. Then, restore consumers from a snapshot (or from the beginning of the topic) and reprocess. This is the final technique for repairing bad data, and it’s also the most labor-intensive and expensive. We’ll cover this more in the final section as it technically also applies to state events.</li></ol><p>Both options require you to identify every single offset for each bad delta event, a task that varies in difficulty depending on the quantity and scope of bad events. The larger the data set and the more delta events you have, the more costly it becomes — especially if you have bad data across a large keyspace.</p><p>These strategies are really about making the best out of a bad situation. I won’t mince words: <strong><em>Bad delta events are very difficult to fix without intensive intervention!</em></strong></p><p>But let’s look at each of these strategies in turn. First up, build-forward, and then to cap off this blog, rewind, rebuild, and retry.</p><h3>Build-Forward: Undo bad deltas with new deltas</h3><p>Deltas, by definition, create a tight coupling between the delta event models and the business logic of consumer(s). There is only one way to compute the correct state, and an infinite amount of ways to compute the incorrect state. And some incorrect states are terminal — a package, once sent, can’t be unsent, nor can a car <a href="https://www.youtube.com/watch?v=7rdL5pKvsss">crushed into a cube be un-cubed</a>.</p><p>Any new delta events, published to reverse previous bad deltas, must put our consumers back to the correct good state without overshooting into another bad state. But it’s very challenging to guarantee that the published corrections will fix your consumer’s derived state. You would need to audit each consumer’s code and investigate the current state of their deployed systems to ensure that your corrections would indeed correct their derived state. It’s honestly just really quite messy and labor-intensive, and will cost a lot in both developer-hours and opportunity costs.</p><p><em>However…</em> you may find success in using a delta-strategy if the producer and consumer are tightly coupled and under the control of the same team. Why? Because you control entirely the production, transmission, and consumption of the events, and it’s up to you to not shoot yourself in the foot.</p><h4>Fixing Delta-Style Events sounds painful</h4><p>Yeah, it is. It’s one of the reasons why I advocate so strongly for state-style events. It’s so much easier to recover from bad data, to delete records (hello GDPR), to reduce complexity, and to ensure loose coupling between domains and services.</p><p>Deltas are popularly used as the <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/event-sourcing">basis of event sourcing</a>, where the deltas form a narrative of all changes that have happened in the system. Delta-like events have also played a role in informing other systems of changes, but may require the interested parties to query an API to obtain more information. Deltas have historically been popular as a means of reducing disk and network usage, but as we observed when discussing state events, these resources are pretty cheap nowadays and we can be a bit more verbose in what we put in our events.</p><p>Overall, I recommend avoiding deltas unless you absolutely need them (e.g., event sourcing). Event-carried state transfer and state-type events work extremely well and simplify so much about dealing with bad data, business logic changes, and schema changes. I caution you to think very carefully about introducing deltas into your inter-service communication patterns, and encourage you to only do so if you own both the producer and the consumer.</p><h4>For Your Information: “Can I just include the state in the delta?”</h4><p>I’ve also been asked if we can use events like the following, where there is a delta AND some state. I call these <strong>hybrid events, </strong>but the reality is that they provide guarantees that are effectively identical to <strong>state events</strong>. Hybrid events give your consumers some options as to how they store state and how they react. Let’s look at a simple money-based example.</p><pre>Key: {accountId: 6232729}<br>Value: {debitAmount: 100, newTotal: 300}</pre><p>In this example, the event contains both the <strong>debitAmount</strong> ($100) and the <strong>newTotal</strong> of funds ($300). But note that by providing the computed state (<strong>newTotal</strong>=$300), it frees the consumers from computing it themselves, just like plain old state events. There’s still a chance the consumer will build a bad aggregate using debitAmount, but that’s on them — you already provided them with the correct computed state.</p><p>There’s not much point in only <em>sometimes</em> including the current state. Either your consumers are going to depend on it all the time (state event) or not at all (delta event). You may say you want to reduce the data transfer over the wire — fine. But the vast majority of time we’re only talking about a handful of bytes, and I encourage you not to worry too much about event size until it’s costing you enough money to bother addressing. If you’re REALLY concerned, you can always invest into a <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/claim-check">claim-check pattern</a>.</p><p>But let’s move on now to our last bad-data-fixing strategy.</p><h3>The Last Resort: Rewind, Rebuild, and Retry</h3><p>Our last strategy is one that you can apply to any topic with bad data, be it delta, state, or hybrid. It’s expensive and risky. It’s a labor-intensive operation that costs a lot of people hours. It’s easy to screw up, and doing it once will make you never want to do it again. If you’re at this point you’ve already had to rule out our previous strategies.</p><p>Let’s just look at two example scenarios and how we would go about fixing the bad data.</p><h4>Rewind, Rebuild, and Retry from an External Source</h4><p>In this scenario, there’s an external source from which you can rebuild your data. For example, consider an nginx or gateway server, where we parse each row of the log into its own well-defined event.</p><p>What caused the bad data? We deployed a new logging configuration that changed the format of the logs, but we failed to update the parser in lockstep (tests, anyone?). The server log file remains the replayable source of truth, but all of our derived events from a given point in time onwards are malformed and must be repaired.</p><p><strong>Solution:</strong></p><p>If your parser/producer is using<strong> schemas and data quality checks</strong>, then you could have shunted the bad data to a DLQ. You would have protected your consumers from the bad data, but delayed their progress. Repairing the data in this case is simply a matter of updating your parser to accommodate the new log format and reprocessing the log files. The parser produces correct events, sufficient schema and data quality, and your consumers can pick up where they left off (though they still need to contend with the fact that the data is late).</p><p>But what happens if you didn’t protect the consumers from bad data, and they’ve gone and ingested it? You can’t feed them hydrogen peroxide to make them vomit it back up can you?</p><p>Let’s check how we’ve gotten here before going further:</p><ul><li>No schemas (otherwise would have failed to produce the events)</li><li>No data quality checks (ditto)</li><li>Data is not compactable and the events have no keys</li><li>Consumers have gotten into a bad state because of the bad data</li></ul><p>At this point your stream is so contaminated that there’s nothing left to do but purge the whole thing and rebuild it from the original log files. Your consumers are also in a bad state, so they’re going to need to reset either to the beginning of time, or to a snapshot of internal state and input offset positions.</p><p>Restoring your consumers from a snapshot or savepoint requires planning ahead (<strong>prevention</strong>, anyone?). Examples include <a href="https://nightlies.apache.org/flink/flink-docs-master/docs/ops/state/savepoints/">Flink savepoints</a>, <a href="https://dev.mysql.com/doc/mysql-replication-excerpt/8.3/en/replication-howto-mysqldump.html">MySQL snapshots</a>, and <a href="https://www.postgresql.org/docs/current/backup-file.html">PostgreSQL snapshots</a>, to name just a few. In either case, you’ll need to ensure that your Kafka consumer offsets are synced up with the snapshot’s state. For Flink, the offsets are stored along with the internal state. With MySQL or PostgreSQL, you’ll need to commit and restore the offsets into the database, to align with the internal state. If you have a different data store, you’ll have to figure out the snapshotting and restores on your own.</p><p>As mentioned earlier, this is a very expensive and time-consuming resolution to your scenario, but there’s not much else to expect if you use no preventative measures and no state-based compaction. You’re just going to have to pay the price.</p><h4>Rewind, Rebuild, and Retry with the Topic as the Source</h4><p>If your topic is your one and only source, then any bad data is your fault and your fault alone. If your events have keys and are compactable, then just publish the good data over top of the bad. Done. But let’s say we can’t compact the data, because it doesn’t represent state? Instead, let’s say it represents <strong>measurements</strong>.</p><p>Consider this <strong>scenario</strong>. You have a customer-facing application that emits <strong><em>measurements of user behavior</em></strong> to the event stream (think clickstream analytics). The data is written directly to an event stream through a gateway, making the event stream the single source of truth. But because you didn’t write tests nor use a schema, the data has accidentally been malformed directly in the topic. So now what?</p><p><strong>Solution:</strong></p><p>The only thing you can do here is reprocess the “bad data” topic into a new “good data” topic. Just as when using an external source, you’re going to have to identify all of the bad data, such as by a unique characteristic in the malformed data. You’ll need to create a new topic and a stream processor to convert the bad data into good data.</p><p>This solution assumes that all of the necessary data is available in the event. If that is not the case, then there’s little you can do about it. The data is gone. This is not CSI:Miami where you can yell “enhance!” to magically pull the data out of nowhere.</p><p>So let’s assume you’ve fixed the data and pushed it to a new topic. Now all you need to do is port the producer over, then migrate all of the existing consumers. But don’t delete your old stream yet. You may have made a mistake migrating it to the new stream, and may need to fix it again.</p><p>Migrating consumers isn’t easy. A polytechnical company will have many different languages, frameworks, and databases in use in their consumers. To migrate consumers, for example, we typically must:</p><ol><li>Stop each consumer, and reload their internal state from a snapshot made prior to the timestamps of the first bad data.</li><li>That snapshot must align with the offsets of the input topics, such that the consumer will process each event exactly once. Not all stream processors can guarantee this (but it is something that Flink is good at, for example).</li><li>But wait! You created a new topic that filtered out bad data (or added missing data). Thus, you’ll need to map the offsets from the original source topic to the new offsets in the new topic.</li><li>Resume processing from the new offset mappings, for each consumer.</li></ol><p>If your application doesn’t have a database snapshot, then we must delete the entire state of the consumer and rebuild it from the start of time. This is only possible if every input topic contains a full history of all deltas. Introduce even just one non-replayable source and this is no longer possible.</p><h3>Summary</h3><p>In <a href="https://medium.com/@adam.bellemare/preventing-and-fixing-bad-data-in-event-streams-part-1-27bf2a99b48e">Part 1</a>, I covered how we do things in the batch world, and why that doesn’t transfer well to the streaming world. While event stream processing is similar to batch-based processing, there is significant divergence in strategies for handling bad data.</p><p>In batch processing, a bad dataset (or partition of it) can be edited, corrected, and reprocessed after the fact. For example, if my bad data only affected computations pertaining to 2024–04–22, then I can simply delete that day’s worth of data and rebuild it. In batch, no data is immutable, and everything can be blown away and rebuilt as needed. Schemas tend to be optional, imposed only after the raw data lands in the data lake/warehouse. Testing is sparse, and reprocessing is common.</p><p>In streaming, data is immutable once written to the stream. The techniques that we can use to deal with bad data in streaming differ from those in the batch world.</p><ul><li>First is to <strong>prevent bad data from entering the stream.</strong> Robust unit, integration, and contract testing, explicit schemas, schema validation, and data quality checks each play important roles. Prevention remains one of the most cost-effective, efficient, and important strategies for dealing with bad data —to just stop it before it even starts.</li><li>Second is <strong>event design</strong>. Choosing state-type event design allows you to rely on republishing records of the same key with the updated data. You can set up your Kafka broker to compact away old data, eliminating incorrect, redacted, and deleted data (such as for GDPR and CCPA compliance). State events allow you to fix the data once, at the source, and propagate it out to every subscribed consumer with little-to-no extra effort on your part.</li><li>Third and finally is <strong>Rewind, Rebuild, and Retry. </strong>A labor-intensive intervention, this strategy requires you to manually intervene to mitigate the problems of bad data. You must pause consumers and producers, fix and rewrite the data to a new stream, then migrate all parties over to the new stream. It’s expensive and complex, and is best avoided if possible.</li></ul><p>Prevention and good event design will provide the bulk of the value for helping you overcome bad data in your event streams. The most successful streaming organizations I’ve worked with embrace these principles and have integrated them into their normal event-driven application development cycle. The least successful ones have no standards, no schemas, no testing, and no validation — it’s a wild west, and many a foot is shot.</p><p>Anyways, if you have any scenarios or questions about bad data and streaming, please reach out to me on <a href="https://www.linkedin.com/in/adambellemare/">LinkedIn</a> or <a href="https://twitter.com/AdamBellemare">Twitter</a>. My goal is to help tear down misconceptions and address concerns around bad data and streaming, and to help you build up confidence and good practices for your own use cases. Also, feel free to let me know what other topics you’d like me to write about, I’m always open to suggestions.</p><p><em>The views expressed in this article are those of the author and do not necessarily reflect the position of Confluent.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526e459c7c6f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/confluent/preventing-and-fixing-bad-data-in-event-streams-part-2-526e459c7c6f">Preventing and Fixing Bad Data in Event Streams — Part 2</a> was originally published in <a href="https://medium.com/confluent">Confluent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing and Fixing Bad Data in Event Streams — Part 1]]></title>
            <link>https://medium.com/confluent/preventing-and-fixing-bad-data-in-event-streams-part-1-27bf2a99b48e?source=rss-d53537b5589d------2</link>
            <guid isPermaLink="false">https://medium.com/p/27bf2a99b48e</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Adam Bellemare]]></dc:creator>
            <pubDate>Wed, 08 May 2024 11:46:57 GMT</pubDate>
            <atom:updated>2024-06-26T19:21:26.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preventing and Fixing Bad Data in Event Streams — Part 1</h3><p>At a high level, <strong>bad data</strong> is data that doesn’t conform to <em>what is expected</em>. For example, an email address without the “<strong>@</strong>”, or a credit card expiry where the MM/YY format is swapped to YY/MM. “Bad” can also include malformed and corrupted data, such that it’s completely indecipherable, and effectively garbage.</p><p>In any case, bad data can cause serious issues and outages for all downstream data users, such as data analysts, scientists, engineers, and ML &amp; AI practitioners. In this blog we’ll take a look at how bad data may come to be, and how we can deal with it when it comes to event streams.</p><p>Event streams in Apache Kafka are predicated on an <em>immutable log</em>, where data, once written, cannot be edited or deleted (outside of expiry or <a href="https://kafka.apache.org/documentation/#compaction">compaction</a> — more on this later). The benefit is that consumers can read the events independently, at their own pace, and not worry about data being modified after they have already read it. The downside is that it makes it trickier to deal with “bad data,” as we can’t simply reach in and edit it once it’s in there.</p><p>In this post, we look at bad data in relation to event streams. How does bad data end up in an event stream? What can we do about it? What’s the impact on our downstream consumers, and how can we fix it?</p><p>First, let’s take a look at the <strong>batch processing world</strong>, to see how they handle bad data, and what we can learn from them.</p><h3>Bad data in batch processing</h3><p>What is batch processing? <a href="https://community.databricks.com/t5/technical-blog/beginners-guide-to-databricks-batch-processing-and-streaming/ba-p/38701">Let’s quote Databricks</a>, and go with:</p><blockquote><em>Batch Processing is a process of running repetitive, high volume data jobs in a group on an ad-hoc or scheduled basis. Simply put, it is the process of collecting, storing and transforming the data at regular intervals.</em></blockquote><p>Batch processing jobs typically rely on <strong>extracting</strong> data from a source, <strong>transforming</strong> it in some way, then<strong> loading</strong> it into a database (<strong>ETL</strong>). Alternately, you can load it into the destination <em>before</em> you transform any of the data, in a recently trendy mode of operations known as <strong>ELT (</strong>by the way, data lake/warehouse people <strong><em>LOVE</em></strong> this pattern as they get all the $$$ from the transform)<strong>.</strong></p><p>A friend and former colleague <a href="https://rmoff.net/2022/10/02/data-engineering-in-2022-architectures-terminology/">wrote more about ELTs and ETLs here</a>, so take a look if you want to see another data expert’s evaluation. The gist, though, is that we get data from “out there” and bring it into “here,” our data lake or warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*73Ipy8H2HoaqIBqS" /></figure><p>In this figure, a <strong>periodic batch job</strong> kicks off, processes the data that lands in the landing table, and does something useful with it — like figuring out how much money the company is owed (or how much your data lake is costing you). Accomplishing this requires a reliable source of data — but whose job is it to ensure that the data powering the data lake is trustworthy and high quality?</p><p>To cut to the chase, the <em>data (or analytics) engineers</em> in the data lake are responsible for getting data from across the company, pulling it in, and then sorting it out into a trustworthy and reliable format. They have little to no control over any of the changes made in production land.</p><p>Data engineers typically engage in significant break-fix work keeping the lights on and the pipelines up and running. I would know, as I did this type of work for nearly 10 years. We’d typically apply schemas to the data once it lands in the data lake, meaning that changes to the source database table in production land may (likely will) break the data sources in the data lake. Data engineers spend nights and weekends fixing malfunctioning data pipelines, broken just hours ago by the 5 p.m. database migration.</p><p>Why are the data engineers responsible for applying schemas? The operational system owners have historically had no responsibility for data once it has crossed out of the source application boundary. Additionally, the data engineers taking the data out of the operational system are performing a “smash ‘n grab,” taking the data wholesale from the underlying database tables. It’s no surprise then that the operational team, with no responsibility for data modeling outside of their system, causes a breakage through a perfectly reasonable database change.</p><p>The following figure shows how a broken ETL job (1) can cause bad data to show up in the landing table (2), eventually resulting in (3) bad results. The exact reason for a broken ETL can vary, but let’s just say in this case it’s due to a change in types in the <strong>source database table </strong>(an <strong>int</strong> is now a <strong>string</strong>) that causes type-checking errors downstream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n0MyF_AUxMIQlEYH" /></figure><p>Once the data engineers spring from their beds and leap into action at three in the morning (when all data problems naturally occur), they can proceed to fix the ETL (4) by adding logic to handle the unexpected change. Next, they reprocess the failed batch to fix the landing table data (5), then rerun the job (6) that recomputes the results table (7) for the affected rows.</p><p>For instance, say (7 — above) is a Hive-declared table containing daily sales aggregates. I’m only going to delete and recompute the aggregates that I know (or think) are incorrect. I won’t drop the whole table and delete all the data if only a known subset is affected. I’ll just surgically remove the bad days (e.g., April 19 to 21, 2024), reprocess (6 — above) for that time range, and then move on to reprocessing the affected downstream dependencies.</p><p>Batch processing relies <strong>extensively</strong> on cutting out bad data and selectively replacing it with good data. You reach right into that great big data set, rip out whatever you deem as bad, then fill in the gap with good data — via reprocessing or pulling it back out of the source.</p><p><strong>Bad data in contaminated data sets<br></strong>The jobs that are downstream of this now-fixed data set must also be rerun, as their own results are also based on bad input data. The downstream data sets are <strong>contaminated</strong>, as are any jobs that run off of a contaminated data set. This is actually a pretty big problem in all of data engineering, and is why tools like <strong>dbt, </strong>and services like Databricks’s <strong>Delta Tables</strong> and Snowflake’s <strong>Dynamic Tables</strong> are useful — you can force recomputation of all dependent downstream jobs, including dumping bad data sets and rebuilding them from the source.</p><p>But I digress. The important thing to note here is that once you get bad data into your data lake, it spreads quickly and easily, and contaminates everything it touches. I’m not going to solve this problem here for you in this blog, however, but I do want you to be aware that it’s not always as simple as “cut out the bad, put in the good!” for fixing bad data sets. The reality is a lot messier, and that’s a whole other can of worms that I’m just going to acknowledge as existing, and move on.</p><p><strong>Incremental batch processing<br></strong>One more word about processing data in batches. Many people have correctly figured out that it’s cheaper, faster, and easier to process your data in small increments, and have named it <a href="https://www.databricks.com/blog/2021/08/30/how-incremental-etl-makes-life-simpler-with-data-lakes.html">incremental processing</a>. An incremental processing job reads in new data, then applies it to its current state based on its business logic. For example, computing the most popular advertisements in 2024 would simply require a running tally of (<strong>advertisementId, clickCount</strong>), merging in the new events as they arrive.</p><p>However, let’s say that you had bad data as an input to your incremental job — say we’ve incorrectly parsed some of the click data and attributed them to the wrong <strong>advertisementId</strong>. To fix our downstream computations, we’d have to issue <strong>unclick</strong> data, telling them to “remove X clicks from these ads, then add X clicks to these other ads.”</p><p>While sure, it’s <em>possible</em> we could wire up some code to do that, the reality is we’re going to keep it simple: Stop everything, blow all the bad data away, rebuild it with good data, then reprocess all the jobs that were affected by it.</p><p>“Hold on,” you might say. “That’s nonsense! Why not just code in removals in your jobs? It can’t be that hard.” Well… kinda. For some jobs with no dependencies you may be correct. But consider for a moment that you have a process computing state beyond just simple addition and subtraction, as pretty much all businesses do.</p><p>Let’s say you’re computing taxes owed for a corporation, and you’re dealing with dozens of different kinds of data sets. The logic for generating the final state of your corporate taxes is winding, treacherous, and not easily reversible. It can be very challenging and risky to code mechanisms to reverse every conceivable state, and the reality is that there will be cases that you simply don’t foresee and forget to code.</p><p>Instead of trying to account for all possible reversal modes, just do what we do with our misbehaving internet routers. Just unplug it, wipe the state, and start it over. Heck, even<a href="https://docs.getdbt.com/best-practices/materializations/4-incremental-models#long-term-considerations"> dbt encourages this approach</a> for misbehaving incremental jobs, <a href="https://docs.getdbt.com/reference/resource-configs/full_refresh">calling it a “full_refresh</a>.”</p><p>Here are the important takeaways as we head into the streaming section.</p><ul><li><strong>There is little prevention against bad data:</strong> <br>The data engineering space has typically been very reactive. Import data of any and all quality now, and let those poor data engineers sort it out later. Enforced schemas, restrictions on production database migrations, and formalized data contracts between the operations and data plane are rarely used.</li><li><strong>The batch world relies on deleting bad data and reprocessing jobs:<br></strong>Data is only immutable until it causes problems, then it’s back to the drawing board to remutate it into a stable format. This is true regardless of incremental or full refresh work.</li></ul><p>I am often asked, “How do we fix bad data in our Kafka topic?” This is one of the big questions I myself asked as I got into event streaming, as I was used to piping unstructured data into a central location to fix up after the fact.</p><p>I’ve definitely learned a lot of what <em>not</em> to do over the years, but the gist is that the strategies and techniques we use for batch-processed data at rest don’t transfer well to event streams. For these, we need a different set of strategies for addressing bad data.</p><p>But before we get to those strategies, let’s briefly examine what happens to your business when you have bad data in your system.</p><h3>Beware the side effects of processing bad data</h3><p>Bad data can lead to bad decisions, both by humans and by services. Regardless of batch processing or streaming, bad data can cause your business to make incorrect decisions. Some decisions are irreversible, but other decisions may not be.</p><p>For one, reports and analytics built on bad data will disagree with those built on good data. Which one is wrong? While you’re busy trying to figure it out, your customer is losing confidence in your business, and may choose to pull out completely from your partnership. While we may call these false reports a side effect, in effect, they can seriously affect the affectations of our customers.</p><p>Alternatively, consider a system that tabulates vehicle loan payments, but incorrectly flags a customer as nonpaying. Those burly men that go to repossess the vehicle don’t work for free, and once you figure out you’ve made a mistake, you’ll have to pay someone to go give it back to them.</p><p>Any decision-making that relies on bad data, whether batch or streaming, can lead to incorrect decisions. The consequences can vary from negligible to catastrophic, and real costs will accrue regardless of if it’s possible to issue corrective action. You must understand that there can be significant negative impacts from using bad data in stream processing, and only some results may be reversible.</p><p>With all that being said, I won’t be able to go into all of the ways you can undo bad decisions made by using bad data. Why? Well, it’s <strong>primarily a business problem</strong>. What does your business do if it makes a bad decision with bad data? Apologize? Refund? Partial Refund? Take the item back? Cancel a booking? Make a new booking?</p><p>You’re just going to have to figure out what your business requirements are for fixing bad data. Then, you can worry about the technology to optimize it. But let’s just get to it and look at the best strategies for mitigating and dealing with bad data in event streams.</p><h3>I’m streaming my life away</h3><p>Event streams are immutable (aside from compaction and expiry). We can’t simply excise the bad data and inject corrected data into the space it used to occupy. So what else can we do?</p><p>The most successful strategies for mitigating and fixing bad data in streams include, in order:</p><ol><li><strong>Prevention:</strong> Prevent bad data from entering the stream in the first place: use schemas, testing, and validation rules. Fail fast and gracefully when data is incorrect.</li><li><strong>Event Design: </strong>Use event designs that let you issue corrections, overwriting previous bad data.</li><li><strong>Rewind, Rebuild, and Retry:</strong> When all else fails.</li></ol><p>In this blog, we’re going to look primarily at <strong>prevention</strong>, covering the remaining strategies in a follow-up post. But to properly discuss these solutions, we need to explore <em>what</em> kind of bad data we’re dealing with and <em>where</em> it comes from. So let’s take a quick side trip into the main types of bad data you can expect to see in an event stream.</p><h3>The main types of bad data in event streams</h3><p>As we go through the types, you may notice a recurring reason for how bad data can get into your event stream. We’ll revisit that at the end of this section.</p><h3>1. Corrupted data</h3><p>The data is simply indecipherable. It’s garbage. It turned into a sequence of bytes with no possible way to retrieve the original data. Data corruption is relatively rare, but may be caused by faulty serializers that convert data objects into a plain array of bytes for Kafka. Luckily, you can test for that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kM70spyHKEnxmlHo" /></figure><h3>2. Event has no schema</h3><p>Someone has decided to send events with no schema. How do you know what’s “good data” and what’s “bad data,” if there are no structure, types, names, requirements, or limitations?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r-0EqcU76O-z8ws4" /></figure><h3>3. Event has an invalid schema</h3><p>Your event’s purported schema can’t be applied to the data. For example, you’re using the <a href="https://docs.confluent.io/platform/current/schema-registry/index.html">Confluent Schema Registry</a> with Kafka, but your event’s Schema Id doesn’t correspond to a valid schema. It is possible you deleted your schema, or that your serializer has inserted the wrong Schema Id (perhaps for a different schema registry, in a staging or testing environment?).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9oNjNhl0l8IZu-vv" /></figure><h3>4. Incompatible schema evolution</h3><p>You’re using a schema (hooray!), but the consumer cannot convert the schema into a suitable format. The event is deserializable, but not mappable to the schema that the consumer expects. This is usually because your source has undergone breaking schema evolution (<a href="https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html#avro-protobuf-and-json-schema-have-different-compatibility-rules">note that evolution rules vary per schema type</a>), but your consumers have not been updated to account for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pmdnZ0z0vKaBPx5B" /></figure><h3>5. Logically invalid value in a field</h3><p>Your event has a field with a value that should never be. For example, an array of integers for “first_name,” or a null in a field declared as a NPE (see below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fwAWztu_vfQsaO5f" /></figure><p>This error type arises when you are not using a well-defined schema, but simply a set of implicit conventions. It can also arise if you are using an invalid, incomplete, old, or homemade library for serialization that ignores parts of your serialization protocol.</p><h3>6. Logically valid but semantically incorrect</h3><p>These types of errors are a bit trickier to catch. For example, you may have a serializable string for a “<strong>first_name</strong>” field (good!), but the name is “<strong>Robert’); DROP TABLE Students; — </strong>”.</p><p>While <a href="https://xkcd.com/327/">little Bobby Tables </a>here is a logically valid answer for a <strong>first_name</strong> field, it is highly unlikely/improbable that this is another one of Elon Musk’s kids. The data in the entry may even be downright damaging.</p><p>The following shows an event with a negative “cost.” What is the consumer supposed to do with an order where the cost is negative? This could be a case of a simple bug that slipped through into production, or something more serious. But since it doesn’t meet expectations, it’s bad data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-eL74KUt1_DOY5ZD" /></figure><p>Some event producer systems are more prone to these types of errors, for example, a service that parses and converts NGINX server logs or customer-submitted YAML/XML files of product inventory into individual events. Malformed sources may be partially responsible for these types of errors.</p><h3>7. Missing events</h3><p>This one is pretty easy. No data was produced, but there should have been something. Right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BPBDKy4J1srXfZeF" /></figure><p>The nice thing about this type of bad data is that it’s fairly easy to prevent via testing. However, it can have quite an impact if only <em>some</em> of the data is missing, making it harder to detect. More on this in a bit.</p><h3>8. Events that should not have been produced</h3><p>There is no undo button to call back an event once it is published to an event stream. We can fence out one source of <a href="https://developer.confluent.io/patterns/event-processing/idempotent-writer/">duplicates with idempotent production</a>, meaning that intermittent failures and producer retries won’t accidentally create duplicates. However, we cannot fence out duplicates that are logically indistinguishable from other events.</p><p>These types of bad events are typically created due to bugs in your producer code. For example, you may have a producer that creates a duplicate of:</p><ul><li>An event that indicates a change or delta (“add 1 to sum”), such that an aggregation of the data leads to an incorrect value.</li><li>An analytics event, such as tracking which advertisements a user clicked on. This will also lead to an overinflation of engagement values.</li><li>An e-commerce order with its own unique <strong>order_id</strong> (see below). It may cause a duplicate order to be shipped (and billed) to a customer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lhidqc7_YmmmsOvS" /></figure><p>While there are likely more types of bad data in event streams that I may have missed, this should give you a good idea of the types of problems we typically run into. Now let’s look at how we can solve these types of bad data, starting with our first strategy:<strong> <em>Prevention</em></strong>.</p><h3>Preventing bad data with schemas, validation, and tests</h3><p>Preventing the entry of bad data into your system is the number one approach to making your life better. Diet and exercise are great, but there’s no better feeling than watching well-structured data seamlessly propagate through your systems.</p><p>First and foremost are schemas. <a href="https://github.com/confluentinc/schema-registry">Confluent Schema Registry</a> supports Avro, Protobuf, and <a href="https://json-schema.org/">JSON Schema</a>. Choose one and use it (I prefer Avro and Protobuf myself). Do yourself, your colleagues, and your future selves a favor. It’s the best investment you’ll ever make.</p><p>There are also other schema registries available, though I personally have primarily used the Confluent one over the years (and also, I work at Confluent). But the gist is the same — make it easy to create, test, validate, and evolve your event schemas.</p><h3>Preventing bad data types 1–5 with schemas and schema evolution</h3><p>Schemas <em>significantly </em>reduce your error incident rates by preventing your producers from writing bad data, making it far easier for your consumers to focus on using the data instead of making best-effort attempts to parse its meaning. Schemas form a big part of <strong><em>preventing bad data</em></strong>, and it’s far, far, <em>far</em> easier to simply prevent bad data from getting into your streams than it is to try to fix it after the damage has already started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*9LOfcBythf7NCmAE" /></figure><p><a href="https://www.json.org/json-en.html">JSON is a lightweight data-interchange format</a>. It is a common yet poor choice for events, but it doesn’t enforce types, mandatory and optional fields, default values, or schema evolution. While JSON has its uses, it’s not for event-driven architectures. Use an explicitly-defined schema such as Avro, Protobuf, or <a href="https://json-schema.org/">JSON Schema</a>.</p><p>Going schemaless (aka using JSON) is like going around naked in public. Sure, you’re “free” of the constraints, boundaries, and limitations, but at what expense? Everyone else has to figure out what the hell is going on, and chaos (and the police) will follow. But reeling back in the hyperbole, the reality is that your consumers <em>need</em> well-defined data. If you send data with a weak or loose schema, it just puts the onus on the consumer to try to figure out what you actually mean.</p><p>Let’s say we have two topics with no schemas and four consumers consuming them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UTIZiQsBH3q5hgIB" /><figcaption>So many chances to screw up the data interpretation!</figcaption></figure><p>There are eight possible chances that a consumer will misinterpret the data from an event stream. And the more consumers and topics you have, the greater the chance they misinterpret data compared to their peers. Not only will your consumers get loud, world-stopping exceptions, but they may also get silent errors — miscalculating sums and misattributing results, leading to undetected divergence of consumer results. These discrepancies regularly pop up in data engineering, such as when one team’s engagement report doesn’t match the other team’s billing report due to divergent interpretations of unstructured data.</p><p>It’s worth contrasting this multi-topic, multi-consumer approach with the typical ETL/ELT pipeline into the data plane. In this streaming model we’re not differentiating <em>who</em> uses the data for what purposes. A consumer is a consumer. In contrast, with ETLs, we’re typically moving data into <em>one</em> major destination, the data lake (or warehouse), so it’s a lot easier to apply a schema to the data after it lands, but before any dependent jobs consume it. With streaming, once it’s in the stream, it’s locked in.</p><p>Implicit schemas, historical conventions, and tribal knowledge are unsuitable for providing data integrity. Use a schema, make it strict, and reduce your consumers’ exposure to unintentional data issues. Once adopted, you can rely on your CI/CD pipelines to perform schema, data, and evolution validation <em>before</em> deploying. The result? No more spewing bad data into your production streams.</p><h3>Data quality rules: Handling type 6: (Logically valid but semantically incorrect)</h3><p>While many of the “bad data” problems can be avoided by using schemas, they are only a partial solution for this type. Sure, we can enforce the correct type (so no more storing Strings in Integer fields), but we can’t guarantee the specific semantics of the data. So what can we do, aside from using a schema?</p><ul><li>Producer unit tests</li><li>Throw Exceptions if malformed (e.g., if phone number is longer than X digits)</li><li>Rely on<strong> </strong><a href="https://docs.confluent.io/cloud/current/sr/fundamentals/data-contracts.html#rules"><strong>Data Contracts and Data Quality Rules</strong></a><strong> </strong>(note: JSON Schema also has some built-in data quality rules)</li></ul><p>Here’s an example of a Confluent data quality rule for a US Social Security Number (SSN).</p><pre>{<br>  &quot;schema&quot;: &quot;…&quot;,<br>  &quot;ruleSet&quot;: {<br>  &quot;domainRules&quot;: [<br>      {<br>        &quot;name&quot;: &quot;checkSsnLen&quot;,<br>        &quot;kind&quot;: &quot;CONDITION&quot;,<br>        &quot;type&quot;: &quot;CEL&quot;,<br>        &quot;mode&quot;: &quot;WRITE&quot;,<br>        &quot;expr&quot;: &quot;size(message.ssn) == 9&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>This rule enforces an exact length of nine characters for the SSN. If it’s an integer, we could also enforce that it must be positive, and if a string, that it must only contain numeric characters.</p><p>The data quality checks are applied when the producer attempts to serialize data into a Kafka record. If the <strong>message.ssn </strong>field is not exactly 9 characters in length, then the serializer will throw an exception. Alternatively, you can also send the record to a dead-letter queue (DLQ) upon failure.</p><p>Approach DLQ usage with caution. Simply shunting the data into a side stream means that you’ll still have to deal with it later, typically by repairing it and resending it. DLQs work best where each event is completely independent, with no relation to any other event in the stream, and ordering is not important. Otherwise, you run the risk of presenting an error-free, yet incomplete, stream of data, which can also lead to its own set of miscalculations and errors!</p><p>Don’t get me wrong. DLQs are a good choice in many scenarios, but they should truly be a last-ditch effort at preventing bad data from getting into a stream. Try to ensure that you test, trial, and foolproof your producer logic to publish your record to Kafka correctly the first time.</p><h3>Testing — Handling types 7 (missing data) and 8 (Data that shouldn’t have been produced)</h3><p>Third in our trio of prevention heroes is <strong>testing</strong>. Write unit and integration tests that exercise your serializers and deserializers, including schema formats (validate against your production schema registry), data validation rules, and the business logic that powers your applications. Integrate producer testing with your CI/CD pipeline so that your applications go through a rigorous evaluation before they’re deployed to production.</p><p>Both <strong>type 7 (missing data)</strong> and <strong>type 8 (data that shouldn’t have been produced)</strong> are actually pretty easy to test against. One of the beautiful things about event-driven systems is that it’s so <em>easy</em> to test them. For integration purposes, you simply produce events on the inputs, wait to see what comes out of the outputs, and evaluate accordingly. Once you find the bug in your logic, write another test to ensure that you don’t get a regression.</p><h3>Summary</h3><p>Bad data can creep into your data sets in a variety of ways.</p><p>Data at rest consists of partitioned files typically backed by a Parquet or ORC format. The data is both created and read by periodically executed batch processes. The files are mutable, which means that bad data can be fixed in place and overwritten, or it can be deleted and regenerated by the upstream batch job.</p><p>Kafka topics, in contrast, are immutable. Once a bad event is written into the event stream, it cannot be surgically removed, altered, or overwritten. Immutability is not a bug but a feature — every consumer gets the same auditable data. But this feature requires that you be careful and deliberate about creating your data.</p><p>Good data practices <strong>prevent</strong> you from getting into trouble in the first place. Write tests, use schemas, use data contracts, and follow schema evolution rules. After your initial investment, you and your colleagues will save so much time, effort, and break-fix work that you’ll actually have time to do some of the fun stuff with data — like getting actual work done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*ly1lZoMlYVkOWSva" /></figure><p><strong>Prevention</strong> is the single most effective strategy for dealing with bad data. Much like most things in life, an ounce of prevention is worth a pound of cure (or 28.3g of prevention and 454g of cure for those of us on the metric system 🇨🇦).</p><p>In the next post, we’ll take a look at leveraging <strong>event design</strong> as part of handling bad data in event streams. There are many ways you can design your events, and we’ll look at a few of the most popular ways and their tradeoffs. Don’t touch that dial, we’ll be right back (yes, TVs used to have dials, and needed time to warm up).</p><p><em>The views expressed in this article are those of the author and do not necessarily reflect the position of Confluent.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27bf2a99b48e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/confluent/preventing-and-fixing-bad-data-in-event-streams-part-1-27bf2a99b48e">Preventing and Fixing Bad Data in Event Streams — Part 1</a> was originally published in <a href="https://medium.com/confluent">Confluent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Streaming and The Problem with Up-Scaling Partition Counts]]></title>
            <link>https://medium.com/@adam.bellemare/event-streaming-and-the-problem-with-up-scaling-partition-counts-301643cf3cb1?source=rss-d53537b5589d------2</link>
            <guid isPermaLink="false">https://medium.com/p/301643cf3cb1</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Adam Bellemare]]></dc:creator>
            <pubDate>Sat, 15 Aug 2020 11:08:42 GMT</pubDate>
            <atom:updated>2020-08-15T11:16:15.007Z</atom:updated>
            <content:encoded><![CDATA[<p>A common goal of distributed and immutable log-based event brokers (such as Apache Kafka, Apache Pulsar, AWS Kinesis, to name a few) is to provide horizontal scaling capabilities for varying workloads. <em>Partitions</em> play an important role in this design, as they enable an application to process just a subset of the event stream. Partitions form the fundamental mechanism for horizontal scaling, as new consumers instances (same application, separate instance) can be created to consume from one or more partitions. Maximum parallelism (the number of concurrent application instances for a single application) is dictated by the number of partitions in an event stream.</p><p>The partition count is typically chosen at the creation time of the event stream. This count is based on a number of factors, including:</p><ul><li>Event Rate — How many events per second?</li><li>Event Rate Growth — How much will this rate grow over time?</li><li>Desired Parallelism — How many parallel consumer instances will be needed?</li><li>Estimated Consumer Processing Rate — Any special considerations about how long these events may take to process?</li><li>Partition Overhead — Event broker and consumer metadata factors impose a <a href="https://blogs.apache.org/kafka/entry/apache-kafka-supports-more-partitions">practical overhead limit on partition count</a>. Defaulting to very high partition counts may not be possible or realistic.</li></ul><p>Partition counts can be easily scaled up by the event-broker admin tools. It is common for an event-stream to be created with an insufficient number of partitions, of with a partition count unsuitable for the growth of the event-stream event rate. Consider the following figure where a single new partition has been added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*LQWYgeeo9iLSNerL.png" /></figure><p>Note that scaling the partition count down is rarely done (and isn’t supported by most event-brokers), as removing a partition will also remove all of its events.</p><h3>Partitions and The Importance of Data Locality</h3><p><em>Data locality</em> is an important <em>convention</em> for the composition of an event-stream. Simply put, all events of <em>the same key</em> must go to <em>the same partition</em>, and is solely the responsibility of the producer.</p><p>Data locality enables full horizontal scaling of consumer systems by providing a very simple data-locality guarantee. This enables a consumer instance to read just a single partition to get all updates for that keyed event, such that it does not need to cross-reference with data from other partitions. This is a fundamental requirement for horizontal scaling of high-throughput systems and enables stateful horizontal scaling and high-throughput capabilities.</p><h3>Factors Prohibiting Scale Up</h3><p>There are a number of system and data factors that prohibit the seamless scaling up of event-stream partitions. These three factors will be the subject of the remainder of this article, and include:</p><ol><li><strong>Consumer and Producer Detection</strong> — Do the consumer and producer applications automatically detect new partition counts? Do the consumers rebalance to allocate processing capacity?</li><li><strong>Keys and Partition Routing</strong> — Are the events keyed? Events of a given key <em>must</em> go the same partition as their predecessors, lest partition data locality be broken.</li><li><strong>Impacts on Consumer State</strong> — Can we scale up without affecting existing state? Unfortunately, for most consumer applications this answer is a definitive “no”.</li></ol><h4>Consumer Detection</h4><p>Increasing the partition count for an event-stream is typically handled by notifying the consumers and producers that a change to the stream metadata has occurred. It is then up to both the consumers and the producer applications to accommodate the new partitions.</p><p>Many consumer applications only generate a list of partitions at application startup time, and maintain a static list throughout the execution of the program. This is commonly due to the convention that event-streams won’t dynamically increase in size during execution, and this assumption is built into many leading frameworks like Apache Spark, Apache Flink, and Apache Beam. For these frameworks, you must halt your application and restart it before the new partitions will be picked up, though of course this may change sometime in the future.</p><h4>Keys and Partition Routing</h4><p>One of the main barriers to seamless partition scaling is that events in the original partitions are not automatically repartitioned (at least not by any distributed event-broker implementations known to me). Reasons for this include:</p><ul><li>Event streams are often too large to repartition without significant impact to the event broker</li><li>The producer is responsible for selecting the partition, and the broker will likely have no knowledge of the partitioning strategy.</li><li>The consumer may have computed state per event key, as is common in stateful event-driven applications. Changing the partition count breaks data locality by routing keyed events to different partitions.</li></ul><p>Once a new partition is added, events of the same key as those already within the event stream may end up distributed to a new partition. This violates the requirement of data locality at the partition level, as is shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/0*s3JD3mgXwhn654an.png" /></figure><p>You may be quick to note that it is the producer’s partitioner algorithm that is responsible for routing events to the partitions, and that perhaps there is a clever way of partitioning that can avoid this problem. I encourage you to keep thinking about this problem, but as it stands, I am unaware of an elegant solution that affords both the increased event-stream parallelism, without necessarily repartitioning existing events (If you happen to come up with an elegant solution to this, please let me know!).</p><h4>Impacts on Consumer State</h4><p>Consumer state, be it derived from a series of keyed events or materialized directly from a keyed entity stream, relies upon guaranteed partition data locality. Consider the addition of a consumer application with internal state stores, scaled to three consumer instances. The following figure illustrates the impact to downstream consumer state when a new partition is added to an existing stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*wClyHB9d2hSlewl9.png" /></figure><p>Violating partition data locality results in two major issues. For one, stale state remains in the original state store (Consumer 0), creating a memory leak and depending on the business application, may result in erroneous calculations. The second issue is that the new state store (Consumer 2) consuming from the new Partition 2 does not have access to any of the previous state for some keys. This can (and usually does) result in invalid state.</p><p>Consider the impact of a series of events tallying a bank account balance. In the case that you, the customer, have your debit and credit events routed to the new partition, you may be surprised to see that your entire credit history has been wiped out. Farewell to your debts, but also, farewell to your previous paycheques.</p><p>While the issues with violating data locality are easy to see with internal state stores, what about if we use an external state store? Would this work any better?</p><h3>Can we use an External State Store to Mitigate Data Locality violations?</h3><p>An external state store is a state store that is materialized outside of the consumer instances. It is durable, its existence is independent of the consumer instances, and it provides each consumer with access to <em>all</em> of the data across <em>all</em> of the key domain (barring issues surrounding eventual consistency, which we won’t cover here). Examples of this include pretty much any and every highly scalable cloud datastore, such as <a href="https://aws.amazon.com/dynamodb/">AWS DynamoDB</a> and <a href="https://cloud.google.com/bigtable">Google BigTable</a> to name a few.</p><p>Unfortunately, even an external state store does not rescue us from our problems, but simply exposes another issue. Consider the same topology with the internal data stores replaced with a single external data store, as shown below (Also note that Consumer 0 is consuming from Partition 1 &amp; 2 in the sake of conserving space in my diagram).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/0*tyEzLw61mDREpng3.png" /></figure><p>There are several significant issues with trying to repair violated partition data locality with an external state store:</p><ul><li>Consumers operate independently of one another, such that events for the same key may be processed out-of-order. Events are only guaranteed processing ordering within a single partition, not between partitions.</li><li>Resetting the state store greatly exacerbates the issue of partition data locality. Consider that a newly expanded event stream will have a far lower volume of events than an old partition. If the state must be rebuilt (due to changing business requirements, or perhaps a bug), events from the new partition may be independently processed significantly earlier than the old partition.</li><li>Temporarily unavailable partitions (due to broker outages) can exacerbate the issue, even if windowing is used. In a case where the partition outage exceeds the windowing duration, out-of-order processing can occur.</li></ul><p>The usage of an external state store shifts the issue of incomplete local data history to one of cross-partition synchronization. You may find the usage of Windowing solutions to be a tempting approach to mitigating this issue, but unfortunately it runs into the scaling barriers of big data.</p><ul><li>No matter how big of a window size you specify for reordering out out-of-order events between the old and new partitions, the difference in event time can always be just slightly larger. This reduces your algorithm’s effectiveness to that of best-effort.</li><li>Very large event streams may have a substantial amount of data over a very long period of time. It may be prohibitively expensive in both raw computing resources to attempt to mitigate this issue.</li><li>While you can identify out-of-order data by means of timestamp comparisons, it can be difficult to maintain sufficient intermediate state to properly accommodate its resolution.</li></ul><p>These windowing / scale issues are best illustrated in the following example, where a new partition is added while the application is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*fk1I_N2PILkHGrpP.png" /></figure><p>In the previous figure you can see that Partition 1 is newly created, and immediately begins to get populated with new red triangle events. Even though a red triangle is produced to Partition 0 at t=50, it is not processed by Consumer 0 before Consumer 1 processes a significant number of red triangles up to t=250. If we suppose that the red triangle event at t=50 is a critical event that <em>must</em> be incorporated into the aggregate state, then we must ask ourselves: “is our application able to maintain sufficient intermediate state to handle out-of-order events?”. In this case, we would need to maintain <em>at least</em> 201 red triangle updates (t=50 to t=250), instead of aggregating them in-order as they arrive.</p><p>Still not convinced? Let’s take a look at your bank balances again, and see what replaying your bank balances would look like from time = 0, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*kqo394pdatvQAl7L.png" /></figure><p>Since both Consumer 0 and Consumer 1 function fully independently, Consumer 1 immediately registers your -$45k transaction first, throwing your account into deficit and locking your out of your banking. Note that you didn’t actually join the bank until t=6,200,000, but that event is in another partition and has not yet been processed. Of course, if we were to force our application to maintain a very large window of events to ensure out-of-order processing results we <em>could</em> possibly catch this error. However, consider if this event-time spans multiple years, and then consider it again if it spans billions of accounts. The sheer volume of intermediate data that would be required to maintain this becomes untenable, as often happens in the real of big-data problems.</p><h3>Solution: Create a New Stream</h3><p>Partition data locality is essential for enabling high-volume and horizontal-scaling event-driven applications. In cases where the rate and volume of events is beginning to become too much for the existing event-stream, and where downstream consumer state is important, creating a new event stream with an increased partition count is the simplest way forward.</p><h4>1. Create a new event stream with the desired partition count</h4><p>Use historic growth trends to predict future growth, and select a partition count that is suitable for both current needs and projected needs. Provision your partition counts such that you won’t need to scale up again in the near future.</p><h4>2. Determine a backfill strategy for historical event data</h4><p>The event data in the old stream will need to be ported over to the new stream. This can be done in two main ways:</p><ul><li>If your upstream producer is itself a stream-processor, you may be able to rewind its event-stream inputs to recreate the necessary events. In this case, create a new producer application to write to the new stream, while the old producer application maintains the old stream. (Note: This strategy assumes that the producer is deterministic and that it has access to all of its old data)</li><li>A second option is to consume the events from the old stream and produce them into the new stream using a custom stream processor. Once caught up, the old stream and the new stream will have the same data while preserving partition data locality.</li></ul><h4>3. Migrate the Consumer Applications to the New Stream</h4><p>The consumers now need to move over to the new event stream. For stateful consumer applications this will necessarily mean resetting the state stores and reprocessing the events from the beginning of the input streams. This can be a lengthy process and is best done while the old application remains running. Once the new application is caught up and the state is generated, the old application can be halted and the new one brought into production usage.</p><p>While an external state store do have the advantage of global data locality, the main issue is that all of the offsets of the old event stream partitions have no definitive mappings to the new event stream partitions. In other words, our consumer has no idea where to start consuming the new stream such that it doesn’t introduce duplicate events, or worse, skip over some.</p><p>Now, it may be possible for you to maintain the consumer’s external state by using a system of windowing and timestamps. I cannot advocate this as a default tactic though, as it is certainly case-by-case basis, and it does beg the question as to how much time and risk it would take to do it correctly versus simply rebuilding the state store. Your individual use-cases will vary, and so I leave this up to you.</p><h4>4. Delete or Archive the Old Event Stream</h4><p>Once all consumers are moved off of the old event stream, it is safe to be deleted or archived. Do not keep duplicate copies of data around, as new consumers may inadvertently begin consumption from the old copy.</p><h3>Conclusion</h3><p>Dynamically increasing partition count on an event stream is best preserved for stateless event processing. While scaling up the partition is easy, ensuring downstream consumers are not unduly affected is still a very real and unsolved problem in the space of event-driven architectures. The incomplete mitigation efforts described in this article are restrictive, expensive, best-effort, and must be replicated for each consumer consumer. They impose a significant cost on consumer application developers, and prohibit them from independently selecting the appropriate technology for their application problem space.</p><p>Scaling up an event-stream partition count violates the convention of partition data locality. Given that most consumer designs rely heavily on this to achieve scalability, it is best to fully avoid it altogether. The best way to scale up a stream with increased partition counts is to simply create a new one and migrate the data and the consumers.</p><p>If you’re interested in Event-Driven Microservices and Architectures, <a href="https://www.oreilly.com/library/view/building-event-driven-microservices/9781492057888/">check out my new book</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*yXiyzGiBEhBnnp0h" /></figure><p><em>Originally published at </em><a href="http://adambellemare.com/2020/08/event-streaming-and-the-problem-with-up-scaling-partition-counts"><em>http://adambellemare.com</em></a><em> on August 15, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=301643cf3cb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction to Beacon Data and Maintaining Integrity — Part I]]></title>
            <link>https://medium.com/@adam.bellemare/an-introduction-to-beacon-data-and-maintaining-integrity-part-i-eec18522938c?source=rss-d53537b5589d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eec18522938c</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[event-driven]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Adam Bellemare]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 02:18:20 GMT</pubDate>
            <atom:updated>2018-11-06T15:49:17.800Z</atom:updated>
            <content:encoded><![CDATA[<h3>An Introduction to Beacon Data and Maintaining Integrity — Part I</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*I2x15vhkpgH6pMlST4zfGg.jpeg" /></figure><p>Companies, like Facebook and Google, have been tracking their user’s behavioral events for decades now, generally using cookies in combination with some sort of tracking pixel. These user behavioral events, which I will hereafter call a “beacon” for brevity, are generally tracked by loading a 1x1 pixel into the user’s web page with additional parameters of interest populated into the URL string. There are dozens of applications for beacon data, but I assume you already know why you want to track behavior (i.e., you already know how you want to apply this knowledge).</p><p><strong>What does a Tracking Pixel look like?</strong></p><p>Let’s say we wish to track a user’s unique ID, the product they interacted with, the interaction type (event), and their self-provided postal code (ZIP code for the Americans out there). You would generally wish to collect the following data, considered the beacon data.</p><blockquote>Data: <br> userId=A49FGD <br> productId=738444 <br> postalCode=M7N1J3</blockquote><blockquote>event=click</blockquote><p>The tracking pixel is simply the mechanism that sends the beacon data to the backend. It may look like the following (note the key-value pairs are embedded within the URL):</p><blockquote><a href="http://path/to/trackingpixel.gif?event=click&amp;productId=738444&amp;userId=A49FGD&amp;postalCode=M7N1J3">http://path/to/trackingpixel.gif?event=click&amp;productId=738444&amp;userId=A49FGD&amp;postalCode=M7N1J3</a></blockquote><p>This is known as a Plain-Text Beacon, as the contents are sent in plain text.</p><p>This event would be received over HTTP by a company’s webserver, with the data then parsed and loaded according to their data handling frameworks. Some companies may apply encryption to the data being sent over the wire, whereas others may leave it in the clear if it’s nothing confidential.</p><p><strong>What is beacon data used for?</strong></p><p>Here are some common applications of beacon data:</p><p><strong>Advertising and Billing</strong></p><p>One of the most common use-cases is to embed a pixel into a website to track engagements with the property. Many companies generate revenue by getting users to click through their ads into an underlying property that is owned by another company (e.g., Facebook to Shopify store). They have a pay-per-click or pay-per-engagement model that can be easily collected using these tracking pixels.</p><p><strong>Machine Learning and Recommendations</strong></p><p>Nearly every web company today is using machine learning to generate product recommendations. Beacons provide a rich source of data in the form of a user’s product interests, demographics and geolocation, all of which are then provided as inputs to generate more accurate machine learning predictions.</p><p><strong>Campaign Health Monitoring</strong></p><p>Beacons can act like a heartbeat. They arrive in real-time and provide us with an up-to-date picture of how any given advertising campaign is going. If engagements appear to be lagging behind projected values we can react early and accordingly. We can review the content itself to ensure that advertisements and content are rendered properly, that they are functional, and that there are no bugs in our system code that would prevent us from tracking these beacons.</p><p><strong>Retailer Reporting</strong></p><p>We have an extensive reporting framework built on top of our Beacon data. At Flipp in particular, we have a large number of retail partners who wish to track things like cost-per-click, cost-per-engagement, time-on-flyer, top-X-flyer-items, and a myriad of other metrics, including custom metrics. These reports provide extremely important insight for the retailers into their campaign performance at Flipp and directly influence budget growth. The most important part here is that a retailer must be able to trust the data that we are providing them.</p><p>As you can imagine, organizing this data and ensuring integrity is crucial to trustworthy data. There are a few alternatives in structuring data — I’ll explain what we do at Flipp, and why:</p><p><strong>The Pros and Cons of Unstructured Plain-Text Beacons</strong></p><p>First, a reminder of what the data in a plain text beacon may look like, as part of the URL of the tracking pixel:</p><blockquote>Data: <br> userId=A49FGD <br> productId=738444 <br> postalCode=M7N1J3</blockquote><blockquote>event=click</blockquote><p>This data is referred to as unstructured because there are no enforcement of names, types or domains. The data can be structured however the sender of the beacon desires, for better or worse. There are a number of benefits and drawbacks with this approach.</p><p><strong>The Pros:</strong></p><ul><li>Easy to add new content. Simply add the new key and value.</li><li>Human Readable — Easier to test</li></ul><p><strong>The Cons:</strong></p><p><strong>Typos</strong> <br> Even with rigorous testing, key values can suffer from typos, especially when multiple platforms are trying to use the same format.</p><blockquote>event=click -&gt; evnet=click</blockquote><blockquote>event=click -&gt; event=cilck</blockquote><p><strong>Drifting Value Domains</strong> <br> Your team might start off only sending true/false, but a future release begins to send 1/0… or “yes”/”no”. Perhaps the underlying logic has changed and it could be considered valid, but older data follows the older format.</p><p><strong>Deprecation of Data</strong> <br> Let’s say a feature is removed, and we can now remove a corresponding beacon, a parameter from another beacon, or both. How do we do this without causing a downstream failure, perhaps in reporting code? How can you know the impact of removal?</p><p><strong>Inconsistent Evolutionary Strategies</strong> <br> Let’s say you add a new product type to engage with. For a Flipp-specific example, this could be the addition of coupons alongside of flyers. Do you use the existing “event=engagement” type to track this event? Do you create a new event type? Do you specify a subtype? What are the impacts to the downstream consumers?</p><p><strong>Impacts of Unstructured Plain-Text Data</strong></p><p>At Flipp, we currently use a mixture of Apache Hive and Apache Spark for a large portion of our regular report generating pipelines. We use Hive to define a schema on top of the plain text data for querying by downstream analytics processes and many of our legacy pipelines use this approach.</p><p>Our newer batch pipelines are implemented using Spark, using Dataframes to access the data directly from an HDFS implementation. During this time we have also ported the storage of our data from plain text to Parquet, but the aforementioned downsides of using plain text beacons still follows us into this implementation.</p><p>Say we receive the events below and we wish to insert it into our data store. The events are shown as a table for readability, and I have highlighted the potentially erroneous data in red.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*KpwCOTluwotYpi-a.png" /></figure><p>What do you do with potentially bad data, or data that does not conform to the underlying schema? Do you discard it? Do you transform it? The unfortunate part is that there is no good answer here, or one that will be satisfactory for all of your downstream data consumers.</p><p><strong>Example Consumer 1:</strong> I want to know all of our unique user IDs to determine weekly active users (unique count on userId).</p><p><strong>Example Consumer 2:</strong> I want to know which products are clicked on the most in my Flyer (unique count on productId grouping).</p><p><strong>Example Consumer 3:</strong> I want to know which postal codes have the highest activity (Geo Operations on postal/zip codes).</p><p>The issue is that we can’t tell for certain what a business unit wants to report on, nor can we predict what it is in the future that they would wish to report. If we were to drop any rows that we deem malformed, reporting queries that should be unaffected by the malformed data will be affected.</p><p>On the other hand, if we leave malformed data in the tables, then we leave it up to each consumer of the data to repair it, which leads to costly duplication of logic in each consumer application. Consumer applications begin to harden around their strategies for handling bad data, but with time these strategies tend to diverge and inconsistencies show up.</p><p>A particularly bad way in which these inconsistencies can show up is in divergent customer reporting. A retailer could obtain a set of reports from us where the billing data does not match the engagement data.</p><p>Trust is easy to lose and hard to gain back, so it is in everyone’s interest to keep the data clean.</p><p><strong>What about a Clean Table?</strong></p><p>One approach is to take the malformed data from the input source, clean up any malformations and output it as a clean data source for downstream consumption. At first glance, this seems like a fine idea, and in practice it will work for any malformations that you know about ahead of time. However, this approach falls short in a few areas:</p><p><strong>Doesn’t account for removed fields</strong></p><ul><li>If data is missing, do you populate it? How do you know it’s missing and not simply deprecated?</li></ul><p><strong>Can’t eliminate all typos</strong></p><ul><li>What decision do you make if you’re collecting both “browsertype” and “browser_type” ? Are they the same values or were they renamed for some reason?</li></ul><p><strong>Doesn’t know the range of valid domains for each beacon, especially for data evolution.</strong></p><ul><li>What if true/false becomes true/false/unknown, or true/false/null? Is that a bug or expected change?</li></ul><p>What ends up happening in practice is that the clean table ends up becoming a reactionary system. The Data Engineering team finds out about a data failure or inconsistency either due to batch data quality reports (kinda slow), in real-time (better, but by the time we find out our data is already becoming inconsistent) or when an external client notifies us that something doesn’t look right (worst of all).</p><p>In each of these scenarios we only detect a failure once it has already occurred, at which point we can only react, improve the cleaning process, and reprocess data. When dealing with large amounts of data, this back processing can become expensive.</p><p><strong>So, now what?</strong></p><p>Most of the problem here stems from using plain-text, freely-defined beacons. While it gives developers an unprecedented freedom to collect various parameters, it is tightly coupled to application release cycles, extremely error prone, and simply defers the resolution of data types and schemas to downstream consumers, further introducing errors.</p><p>I’ve covered the first part of how we manage our data at Flipp, and in the second, I’ll unpack how we use Avro to organize our data with event-driven microservice architecture (a pattern used also by LinkedIn and Airbnb). That’s a whole other can of worms — so I’ll write more about it in the second part!</p><p>For now, I recommend looking at how your team’s data is structured — and the kind of problems you’re running into, and how you plan to clean things up or work with a new structure.</p><p><em>Originally published at </em><a href="https://eng.flipp.com/an-introduction-to-beacon-data-and-maintaining-integrity-part-i-2/"><em>eng.flipp.com</em></a><em> on November 6, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eec18522938c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>