<?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 Gary Strange on Medium]]></title>
        <description><![CDATA[Stories by Gary Strange on Medium]]></description>
        <link>https://medium.com/@gary.strange?source=rss-3e25bbe2c359------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZmnJsNOITEehp5kU4j3MJg.jpeg</url>
            <title>Stories by Gary Strange on Medium</title>
            <link>https://medium.com/@gary.strange?source=rss-3e25bbe2c359------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:04:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gary.strange/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[Self-Describing Data Assets]]></title>
            <link>https://medium.com/@gary.strange/self-describing-data-assets-15b1ad0e3b7c?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/15b1ad0e3b7c</guid>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[metadata]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 11:35:15 GMT</pubDate>
            <atom:updated>2024-02-02T10:28:33.269Z</atom:updated>
            <content:encoded><![CDATA[<h4>Find out why collocating crucial metadata alongside data supports data discovery and dynamic data processing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FEXfdmU59yQzOA5q" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Metadata-driven ingestion seems to have created quite a buzz in the data industry lately. Many vendors offer their wares as ‘metadata-driven’. I guess config-driven, template-generated or parameterisation and abstraction just don’t sound that sexy.</p><p>It’s common to see various data processing architectures boast how they are ‘metadata-driven’. Metadata in these data processing architectures might be stored as JSON, YAML and other formats. Some might champion the notion that having all your metadata carefully modelled in a database is an appropriate choice.</p><p>Whilst I have no issue with getting excited about metadata and I’m a big advocator of abstraction and parameterisation. I feel that some metadata is divorced from the data it references and there really isn’t a reason to have such a long-distance relationship. In this article, I’ll make the case for collocated metadata. I’ll give you a working example of how collocated metadata produces self-describing data assets.</p><h3><strong>Metadata Driven Pipelines</strong></h3><p>Environment details, integration end-points, package versions and data destinations are all good examples of metadata that define a data pipeline. Having these pieces of information managed and injected into the data pipeline means pipeline engineers can produce generic and dynamic pipelines. These pipelines can then be uniquely configured to operate as consistent patterns of operation over hundreds or thousands of data entities.</p><p>Now let’s talk about schema. The data schema is metadata. It’s used to precisely describe and manage stored data. It includes fundamental data that describes the data model and maps data attributes to a type system. Richer metadata can also be used to further the definition, more precisely specifying the stored information. For example, ranges (min/max number) can be used to constrain numeric data.</p><p><em>Example JSON schema with additional metadata.</em></p><pre>     {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;required&quot;: [&quot;price&quot;],<br>        &quot;properties&quot;: {<br>          &quot;price&quot;: {<br>            &quot;type&quot;: &quot;number&quot;,<br>            &quot;multipleOf&quot;: 1E-4,<br>            &quot;minimum&quot;: 0,<br>            &quot;maximum&quot;: 99999<br>          }<br>        }<br>      }</pre><p>It is perhaps less common to see the definition of inter-attribute relationships in metadata ( how one attribute in a dataset relates to another ). Perhaps several attributes share a common relationship or categorisation. Perhaps a high Pearson’s correlation coefficient score is known to exist between two attributes. These more advanced data traits are rarely identified in schema although they are often required by analysts to understand the context of the data. There is an argument that some context is too volatile to be defined as schema. Schema after all needs to be robust and non-volatile. Can a correlation coefficient be expected to be stable over time? perhaps, perhaps not. One of the fundamental principles of schema definition must be that it’s stable, non-volatile, information that defines data.</p><h3><strong>Data Entities</strong></h3><p>Nearly all types of data entities will have a natural key. A natural key is one or more entity attributes that uniquely identify a fact (record).</p><p>When a fact mutates it creates a new state that supersedes the previous. Both the current and previous states share the same natural key definition and key values. The continuous mutation of state creates unbounded data.</p><p>For a detailed definition of ‘unbounded data’: <a href="https://www.oreilly.com/radar/the-world-beyond-batch-streaming-101/">Streaming 101: The world beyond batch</a></p><p>Unbounded data can transition into a few lower-fidelity forms. Slowly Changing Dimensions (SCD) and latest state (snapshot) transitions remove data fidelity, lower the velocity and model the data for a wide variety of analytics. If we consider unbounded data to be high-velocity, SCD and snapshots are lower-velocity forms of the entity.</p><p>To compute lower velocity forms of data we must reduce the fidelity by omitting some or all intermediate previous states. A natural key is used to identify a unique record state at a point in time. Unbounded data contains all states of data over time. So the unique natural key is repeated many times in the unbounded data. To acquire the most recent impression of a fact (record) we must discard all previously known states. To identify previously known states each record must adhere to a sequence axis. This might be real-world time, a versioning semantic (ideally lexicographical in form) or a logical sequence number ( monotonic function ). With all known states plotted on an axis, only the most recent record is retained with all other states discarded. In other words, we need to place them in an order. Keep the most recent and discard the rest.</p><p>Metadata that specifies the natural key and sequence axis must be retained in the data processing system. Data should, where practical, be self-subscribing. Therefore the entity metadata and data should be collocated.</p><h3><strong>How to Define Metadata</strong></h3><p>The spark DataFrame API affords metadata storage alongside the DataFrame schema. Ref: <a href="https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/types/MetadataBuilder.html">https://spark.apache.org/docs/latest/api/scala/org/apache/spark/sql/types/MetadataBuilder.html</a></p><p>We will therefore utilise this metadata mechanism to persist and retrieve natural key and sequence axis information. We will see in action later in the code example.</p><p>Let’s start with a very simple shopping model without metadata. The schema for the Order record is as follows…</p><p><em>Example DataType Schema</em></p><pre>schema = StructType([<br>        StructField(&quot;OrderId&quot;,       IntegerType(), True),<br>        StructField(&quot;CustomerId&quot;,    StringType(),  True),<br>        StructField(&quot;EventDateTime&quot;, StringType(),  True),<br>        StructField(&quot;Status&quot;,        StringType(),  True),<br>        StructField(&quot;Items&quot;,         ArrayType&lt;StringType()&gt;,  True)<br>        ])</pre><p>A stream of Order states may look like this…</p><p><em>Example Stream of Orders</em></p><pre>+---------+------------+---------------------+---------+---------------------+<br>| OrderId | CustomerId |    EventDateTime    | Status  |        Items        |<br>+---------+------------+---------------------+---------+---------------------+<br>|       1 | Gary       | 24/12/2023 18:00:00 | Created | {}                  |<br>|       1 | Gary       | 24/12/2023 18:00:01 | Updated | { &quot;Milk&quot; }          |<br>|       1 | Gary       | 24/12/2023 18:00:02 | Updated | { &quot;Milk&quot;, &quot;Bread&quot; } |<br>|       2 | Alexa      | 24/12/2023 18:00:02 | Created | {}                  |<br>+---------+------------+---------------------+---------+---------------------+</pre><p>To understand the current state of my customer Orders I need to reduce the fidelity in this data. I have two customers, Gary and Alexa, so I need two records that show me the state of their Orders.</p><p>The subjects of the transactions are Customer and Order so they make my natural key. My desired information is the latest state, so I need to understand the sequence in which records occurred. The EventDateTime column provides this.</p><p>Let’s look at the same data with the context overlayed ( see the header in the table below ).</p><p><em>Example Ideal Data Format</em></p><pre>+----------------------+---------------------+-------------------------------+<br>|    Natural Key       |    Sequence Key     |   State (non key attributes ) |<br>+---------+------------+---------------------+---------+---------------------+<br>| OrderId | CustomerId |    EventDateTime    | Status  |        Items        |<br>+---------+------------+---------------------+---------+---------------------+<br>|       1 | Gary       | 24/12/2023 18:00:00 | Created | {}                  |<br>|       1 | Gary       | 24/12/2023 18:00:01 | Updated | { &quot;Milk&quot; }          |<br>|       1 | Gary       | 24/12/2023 18:00:02 | Updated | { &quot;Milk&quot;, &quot;Bread&quot; } |<br>|       2 | Alexa      | 24/12/2023 18:00:02 | Created | {}                  |<br>+---------+------------+---------------------+---------+---------------------+</pre><p>Imagine if this was how data was described and visualised in the many tech tools we use to interact with data! No presumptions to be made, no going off to find some documentation in the hope of the fundamental metadata being recorded by a good citizen. No need to visit a secondary system hosting the encyclopaedia of metadata.</p><p>Imagine if this was the way another computer system saw your data. No need for additional context to be explicitly injected into the data processing pipeline. No need to explicitly define keys. The data is describing itself.</p><p>With older data formats, the data pipeline will just see this…</p><p><em>Example Legacy Data Format</em></p><pre>+---------+------------+---------------------+---------+---------------------+<br>|       1 | Gary       | 24/12/2023 18:00:00 | Created | {}                  |<br>|       1 | Gary       | 24/12/2023 18:00:01 | Updated | { &quot;Milk&quot; }          |<br>|       1 | Gary       | 24/12/2023 18:00:02 | Updated | { &quot;Milk&quot;, &quot;Bread&quot; } |<br>|       2 | Alexa      | 24/12/2023 18:00:02 | Created | {}                  |<br>+---------+------------+---------------------+---------+---------------------+</pre><p>Aka CSV.</p><p>With modern data formats (parquet) they’ll see something like this…</p><p><em>Example Modern Data Format</em></p><pre>+---------+------------+---------------------+---------+---------------------+<br>| OrderId | CustomerId |    EventDateTime    | Status  |        Items        |<br>| (long)  | (string)   |    (datetime)       | (string)|   (array&lt;string&gt;)   |<br>+---------+------------+---------------------+---------+---------------------+<br>|       1 | Gary       | 24/12/2023 18:00:00 | Created | {}                  |<br>|       1 | Gary       | 24/12/2023 18:00:01 | Updated | { &quot;Milk&quot; }          |<br>|       1 | Gary       | 24/12/2023 18:00:02 | Updated | { &quot;Milk&quot;, &quot;Bread&quot; } |<br>|       2 | Alexa      | 24/12/2023 18:00:02 | Created | {}                  |<br>+---------+------------+---------------------+---------+---------------------+</pre><p>But what if this evolved? What if richer metadata was available alongside the data, could the receiving system operate patterns without explicit injection of additional context?</p><h4><strong>Smart Functions</strong></h4><p>One of the behavioural advancements Spark offers as a data processing tool, in my opinion, is its default optimism. If spark was a person they would have a sunshine demeanour. Whereas a typical RDMS as a person would be more of a stickler for rules. If anything steps outside of those rules then I’m going to take major issue with it and cross my arms until it’s sorted without compromise. With spark, if you don’t give it a schema, does it put tools down and go on strike? No, it tries to accommodate your lack of information or plain laziness by inferring a schema for you. If you feed Spark one dodgy record in the million you’ve tried to load, does it abort, tell you off and make you start over? No, it optimistically loads the 99.99% good rows.</p><p>Building on this optimistic mindset we can develop smart functions that will try to discover additional metadata when processing data.</p><h4><strong>Example Code</strong></h4><p>If you’ve read this far, thanks for staying with me. Let’s get into some code. For the test case scenario I’ll use the simple Order dataset described above and reduce it to just the latest state.</p><p>Below is a class that has a transform method. This method reduces a DataFrame by selecting the latest state from a sequence of records.</p><p><em>Example Class</em></p><pre>class ReduceToLatestState(ITransformer):<br>    def __init__(self, key_columns = None, sequencer_columns = None):<br>        self._key_columns = key_columns<br>        self._sequencer_columns = sequencer_columns<br><br>    def setKeys(self, schema):<br>        # Infer keys and sequencer information if not explicitly set.<br>        if self._key_columns is None and self._sequencer_columns is None:<br>            self._key_columns, self._sequencer_columns = getNaturalKeyAndSequencerColumns(schema)<br><br>        # If the keys or sequencer information has not been either explicitly set or inferred then raise exception. <br>        if any(param is None or len(param) == 0 for param in [self._key_columns, self._sequencer_columns]):<br>            raise Exception(&quot;Natural Key or Sequencer missing or unable to be inferred.&quot;)<br><br>        return self<br>        <br>    def transform(self, inDf: DataFrame ) -&gt; DataFrame:<br>        self.setKeys(inDf.schema)<br>        return(self._transform(inDf, self._key_columns, self._sequencer_columns))<br><br>    def _transform(self, inDf:DataFrame, key_columns:List[str], sequencer_columns:List[str]):<br>        all_other_columns = columnsNotInColumns(<br>            inDf.columns,<br>            key_columns + sequencer_columns<br>            )<br>        <br>        return (<br>            inDf<br>                .select(*key_columns, struct(sequencer_columns + all_other_columns).alias(&quot;non_key_columns_obj&quot;))<br>                .groupBy(key_columns)<br>                .agg(max(&quot;non_key_columns_obj&quot;).alias(&quot;max_non_key_columns_obj&quot;))<br>                .select(*key_columns, &quot;max_non_key_columns_obj.*&quot;)<br>        )</pre><p><strong>Helper functions</strong></p><p>I have three helper functions. One is a generic function that returns all fields that have a piece of metadata with a specific name. The second attempts to locate the “key” and “sequencer” fields metadata from schema. The order in which fields are processed is important, so the metadata also provides the ordering context using an integer. The third, simply excludes one list of string (columns) from another list of strings.</p><p><em>Example Help Functions</em></p><pre>def fieldsWithMetadata(schema:DataType, metadataKey: str) -&gt; List[StructField]:<br>    return [field for field in schema.fields if metadataKey in field.metadata]<br><br>def getNaturalKeyAndSequencerColumns(schema:DataType) -&gt; (List[str], List[str]):<br>    key_columns = dict(sorted([(field.metadata[&quot;key&quot;],field.name) for field in fieldsWithMetadata(schema, &quot;key&quot;)]))<br><br>    sequencer_columns = dict(sorted([(field.metadata[&quot;sequencer&quot;],field.name) for field in fieldsWithMetadata(schema, &quot;sequencer&quot;)]))<br><br>    return list(key_columns.values()), list(sequencer_columns.values())<br><br>def columnsNotInColumns(inCols: List[str], excludeCols: List[str]) -&gt; List[str]:<br>    return [column for column in inCols if column not in excludeCols]</pre><p>Lets look at a unit test to cover the ‘transform’ method of the ‘ReduceToLatestState’ class.</p><p><em>Example Unit Test (pytest)</em></p><pre>def test_transformers_reducetolateststate_inferred(spark_session):<br>    schema = StructType([<br>        StructField(&quot;OrderId&quot;,       IntegerType(), True, { &quot;key&quot;: 0}),<br>        StructField(&quot;CustomerId&quot;,    StringType(),  True, { &quot;key&quot;: 1}),<br>        StructField(&quot;EventDateTime&quot;, StringType(),  True, { &quot;sequencer&quot; : 0}),<br>        StructField(&quot;Status&quot;,        StringType(),  True),<br>        StructField(&quot;Items&quot;,         ArrayType(StringType()),  True)<br>        ])<br>    df:DataFrame = spark_session.createDataFrame( [( 1, &quot;Gary&quot;, &quot;24/12/2023 18:00:00&quot;, &quot;Created&quot;, []),<br>                                                   ( 1, &quot;Gary&quot;, &quot;24/12/2023 18:00:01&quot;, &quot;Updated&quot;, [&quot;Milk&quot;]),<br>                                                   ( 1, &quot;Gary&quot;, &quot;24/12/2023 18:00:02&quot;, &quot;Updated&quot;, [&quot;Milk&quot;, &quot;Bread&quot;]),<br>                                                   ( 2, &quot;Alexa&quot;, &quot;24/12/2023 18:00:02&quot;, &quot;Created&quot;, [])], schema)                              <br>    <br>    transformer = ReduceToLatestState(  )<br>    #key metadata inferred during transform.<br>    actual_df = df.transform( transformer.transform  )<br><br>    expected_df =  spark_session.createDataFrame( [( 1, &quot;Gary&quot;, &quot;24/12/2023 18:00:02&quot;, &quot;Updated&quot;, [&quot;Milk&quot;, &quot;Bread&quot;]),<br>                                                   ( 2, &quot;Alexa&quot;, &quot;24/12/2023 18:00:02&quot;, &quot;Created&quot;, [])], schema)<br><br>    assert_df_equality(actual_df, expected_df)<br>    assert(True)</pre><p>As you can see the schema is decorated with ‘key’ and ‘sequencer’ metadata. The integers represent the order of the fields within the key. When this schema is used to create a test DataFrame the metadata is collocated with the data. As a result, when the ‘ReduceToLatestState’ transformer is used to process the DataFrame the ‘key’ and ‘sequencer’ metadata can be inferred during the transform.</p><p><em>Example Test Output (expected_df).</em></p><pre>+---------+------------+---------------------+---------+---------------------+<br>| OrderId | CustomerId |    EventDateTime    | Status  |        Items        |<br>| (long)  | (string)   |    (datetime)       | (string)|   (array&lt;string&gt;)   |<br>+---------+------------+---------------------+---------+---------------------+<br>|       1 | Gary       | 24/12/2023 18:00:02 | Updated | { &quot;Milk&quot;, &quot;Bread&quot; } |<br>|       2 | Alexa      | 24/12/2023 18:00:02 | Created | {}                  |<br>+---------+------------+---------------------+---------+---------------------+</pre><p>If I was to write the DataFrame to storage the metadata would persist in the parquet footer. Any subsequent downstream process can take advantage of the richer metadata stored alongside the data.</p><p><em>Example Parquet Footer.</em></p><pre>{<br> &quot;type&quot;: &quot;struct&quot;,<br> &quot;fields&quot;: [<br>  {<br>   &quot;name&quot;: &quot;Id&quot;,<br>   &quot;type&quot;: &quot;long&quot;,<br>   &quot;nullable&quot;: true,<br>   &quot;metadata&quot;: {<br>       &quot;key&quot;: 0<br>      }<br>  },<br>  {<br>   &quot;name&quot;: &quot;InOffice&quot;,<br>   &quot;type&quot;: &quot;long&quot;,<br>   &quot;nullable&quot;: true,<br>   &quot;metadata&quot;: {<br>       &quot;sequencer&quot;: 0<br>      }<br>  },<br>  {<br>   &quot;name&quot;: &quot;Name&quot;,<br>   &quot;type&quot;: &quot;string&quot;,<br>   &quot;nullable&quot;: true,<br>   &quot;metadata&quot;: {}<br>  }<br> ]<br>}</pre><h3>Final Thoughts</h3><p>One of the advantages of using collocated metadata like this is the self-describing qualities. Downstream systems like other spark pipelines, data quality services, BI serving layers, ML models, data governance tooling and citizen data users can all benefit from the richer metadata. If we think of scenarios that stretch beyond the enterprise, business partners that are sharing data can also benefit from crucial metadata being made available alongside data.</p><p>Metadata will drive the Data Intelligence Platform of the future. We should expect massive strives in data engineering and ML engineering through intelligent productivity. As we know all things intelligent are fuelled by data. The more data we feed in, the more intelligent they become. That includes metadata.</p><h4>Information Schema and Check Constraints</h4><p>Although, still in private preview, Databricks is adding primary key and time-series constraints to the SQL dialect. Perhaps, in the future, there will be a way to achieve a similar self-describing trait that drives dynamic data engineering pipelines within the Databricks product.</p><h4>Delta Live Tables</h4><p>Databricks Delta Live Tables (DLT) include a pipeline operation called APPLY CHANGE INTO. The Delta Table Change Data Feed (CDF) is utilised to merge changes from a source table into a target table. This operation allows pipeline developers to declare KEYS and a SEQUENCE BY clause. Whilst I think this is a great addition to DLT this integral information is baked into the pipeline and does not persist in the data meta-data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15b1ad0e3b7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Data Lake Usage Monitoring]]></title>
            <link>https://medium.com/analytics-vidhya/azure-data-lake-usage-monitoring-1d1c947f2865?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d1c947f2865</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 10:55:48 GMT</pubDate>
            <atom:updated>2023-03-22T09:26:32.133Z</atom:updated>
            <content:encoded><![CDATA[<p>If the pick-n-mix was left un-monitored would you gobble down a sneaky cola bottle?</p><p>In this article, I’ll attempt to surface some of the psychology involved in Enterprise Data Governance challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*lLk3_lfm2zPA_8_SuHK6Zg.png" /><figcaption>Yummy!</figcaption></figure><h4>Pick n Mix</h4><p>Imagine you’re stood next to the pick-n-mix section just at the side of a large cinema foyer. The place is deserted as it&#39;s mid-movie, there are no CCTV cameras and a solitary cola bottle is staring right up at you. Would you gobble it up? It’s so tasty, no one would know and it’s only pennies in value.</p><p>Maybe you would, maybe you wouldn’t. The point is that humans are risk assessment machines. Constantly reevaluating risk to survive. When there is no threat of being found out, no foreseen consequences, and an easy reward, humans will act.</p><h4><strong>Data</strong></h4><p>If left to it, would these risk assessment machines decide it would be ‘ok’ to do something they probably shouldn’t be doing with data to achieve an easy reward? Perhaps a conscious decision of malicious intent, carelessness, or even lack of understanding. If they understood that they could be held to account, would that change the decisions they make? Would they be more careful? Would they seek advice before proceeding with an action they don’t fully understand?</p><p>This is more important now we have Data Lakes and information-driven organisations. Every team and every individual within the organisation is empowered to do great things with data. We want the enterprise to experiment with a rich reservoir of data at its fingertips. A pessimistic approach is to serve data on a need-to-know basis. Prove you understand and need to use this data. Prove it is for a good cause and then you can have access. Thus, demonstrating you have already been made to account for your actions before you take them. A more optimistic proposal is to encourage expedited data discovery and frictionless data access, whilst retaining governance by demonstrating accountability is an active, continuous, observable process.</p><p>Let’s park those thoughts for a moment and get into some technology.</p><h4>Who, What, When, Where, Why</h4><p>The five W’s help define factual information. If we’re able to record these five related attributes at the time data is being interacted with, then we can establish data consumption and usage facts.</p><p>I will show you how I was able to use the logging data built into Azure Data Lake Storage Gen2 to gain greater observability over data access.</p><p>Here is a screenshot from one of the Power BI visualisation generated from the Data Lake diagnostic log I was able to construct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzQh6xQcJrxCpne5fNNlWw.png" /><figcaption>Data Lake log information visualised in Power BI</figcaption></figure><p>Let me explain the elements of the visual. In the left panel, I have all the containers within the Data Lake listed. For each, container there is a stacked bar representing the number of blob read requests made to a sub-folder of the container. Each coloured stack bar has an integer value in white text. This integer represents the number of active user principals in the period.</p><p>So for the ‘salesorderservice’ container ( red box ), there was a total of 265 million read requests. Within the ‘salesorderserivce’ container I have seven coloured stack bars representing sub-folders (datasets) within the container. The selected solid green bar which represents one of the datasets has the highest number of active user principles (31).</p><p>On the far right ( yellow box ) I have a legend of all the sub-folders within the ’salesorderservice’ container and the graph in the centre of the screen shows the related read requests trend over time.</p><p>At the bottom of the visual ( blue box ), there is a table of user principles and the number of read requests made against the sub-folders (datasets) in the ‘salesorderservice’ blob container. In the smaller blue box, you can see the number of read requests I made against the order booked dataset ( 156750 requests ).</p><h4>Processing Data Lake Logs</h4><p>A ton of useful information is automatically captured by the Azure Data Lake Storage service and stored in the special system container $logs.</p><p>Just take a look at this link to understand just how much is getting captured and stored away for diagnostics and intelligence. <a href="https://learn.microsoft.com/en-us/rest/api/storageservices/storage-analytics-logged-operations-and-status-messages#logged-operations">https://learn.microsoft.com/en-us/rest/api/storageservices/storage-analytics-logged-operations-and-status-messages#logged-operations</a></p><p>It&#39;s possible to use a fairly simple architecture to process the logs and develop incredibly insightful dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*cUumJ_CC89TcYSbvwLTDoA.png" /><figcaption>Basic Azure Data Lake Log Processing Architecture</figcaption></figure><p>At the heart of this solution, I have a fairly simple Databricks notebook written in a combination of Pyspark and SQL. I use Pyspark for the imperative and functional code operations and I use the mite of SQL to declare how columns of data will be crunched.</p><p>The output of the data crunching is stored in a blob storage account. Power BI connects to the blob storage account to acquire data for the visuals. Blob storage is a good choice here for a few reasons. It’s cheap, it&#39;s reliable ( check the SLAs ) and we only need to refresh the data periodically throughout the day. Another alternative might be to call hive/Unity Catalog objects in Databricks directly from Power BI. But this would mean the data crunching would only happen at Power BI refresh time. I want to pre-crunch the data on a schedule.</p><p>Whilst the Azure Data Lake logs give us a lot of useful information they don’t provide human-friendly security principal identifiers. So we need Microsoft Graph to tell us the user-friendly identity of the principals appearing in the logs.</p><h4>Databricks Notebook</h4><p>Microsoft has documented the Azure Data Lake logs csv schema here:</p><p><a href="https://learn.microsoft.com/en-us/rest/api/storageservices/storage-analytics-log-format#log-entry-format-20">Storage Analytics log format (REST API) - Azure Storage</a></p><p>Which I converted to a struct type that can be used to parse the log data.</p><pre>from pyspark.sql.types import StructType, StructField, LongType, StringType, ArrayType, TimestampType<br><br>diagnosticLogRecordv2 =StructType([<br>  StructField(&#39;versionnumber&#39;,StringType(),True),<br>  StructField(&#39;requeststarttime&#39;,TimestampType(),True),<br>  StructField(&#39;operationtype&#39;,StringType(),True),<br>  StructField(&#39;requeststatus&#39;,StringType(),True),<br>  StructField(&#39;httpstatuscode&#39;,StringType(),True),<br>  StructField(&#39;endtoendlatencyinms&#39;,StringType(),True),<br>  StructField(&#39;serverlatencyinms&#39;,StringType(),True),<br>  StructField(&#39;authenticationtype&#39;,StringType(),True),<br>  StructField(&#39;requesteraccountname&#39;,StringType(),True),<br>  StructField(&#39;owneraccountname&#39;,StringType(),True),<br>  StructField(&#39;servicetype&#39;,StringType(),True),<br>  StructField(&#39;requesturl&#39;,StringType(),True),<br>  StructField(&#39;requestedobjectkey&#39;,StringType(),True),<br>  StructField(&#39;requestidheader&#39;,StringType(),True),<br>  StructField(&#39;operationcount&#39;,StringType(),True),<br>  StructField(&#39;requesteripaddress&#39;,StringType(),True),<br>  StructField(&#39;requestversionheader&#39;,StringType(),True),<br>  StructField(&#39;requestheadersize&#39;,StringType(),True),<br>  StructField(&#39;requestpacketsize&#39;,StringType(),True),<br>  StructField(&#39;responseheadersize&#39;,StringType(),True),<br>  StructField(&#39;responsepacketsize&#39;,StringType(),True),<br>  StructField(&#39;requestcontentlength&#39;,StringType(),True),<br>  StructField(&#39;requestmd5&#39;,StringType(),True),<br>  StructField(&#39;servermd5&#39;,StringType(),True),<br>  StructField(&#39;etagidentifier&#39;,StringType(),True),<br>  StructField(&#39;lastmodifiedtime&#39;,StringType(),True),<br>  StructField(&#39;conditionsused&#39;,StringType(),True),<br>  StructField(&#39;useragentheader&#39;,StringType(),True),<br>  StructField(&#39;referrerheader&#39;,StringType(),True),<br>  StructField(&#39;clientrequestid&#39;,StringType(),True),<br>  StructField(&#39;userobjectid&#39;,StringType(),True),<br>  StructField(&#39;tenantid&#39;,StringType(),True),<br>  StructField(&#39;applicationid&#39;,StringType(),True),<br>  StructField(&#39;audience&#39;,StringType(),True),<br>  StructField(&#39;issuer&#39;,StringType(),True),<br>  StructField(&#39;userprincipalname&#39;,StringType(),True),<br>  StructField(&#39;reservedfield&#39;,StringType(),True),<br>  StructField(&#39;authorizationdetail&#39;,StringType(),True)<br>])                                   ])</pre><p>For simplicity of parsing, I have changed a few of the field types to string. Log data typically sits in the semi-structured category so the decision to loosely type using string was tactical. Looking back, the log data conforms to a well-structured, seldom-changing, schema. So perhaps this tactic wasn’t necessary.</p><p>The next job is to configure access to the $logs container. An Azure Service Principal is used to authenticate.</p><pre>def setBlobOAuthConfig( storageaccountname: str, applicationid:str, directoryid:str, secret:str ) :<br>  spark.conf.set(f&quot;fs.azure.account.auth.type.{storageaccountname}&quot;, &quot;OAuth&quot;)<br>  spark.conf.set(f&quot;fs.azure.account.oauth.provider.type.{storageaccountname}&quot;, &quot;org.apache.hadoop.fs.azurebfs.oauth2.ClientCredsTokenProvider&quot;)<br>  spark.conf.set(f&quot;fs.azure.account.oauth2.client.id.{storageaccountname}&quot;, f&quot;{applicationid}&quot;)<br>  spark.conf.set(f&quot;fs.azure.account.oauth2.client.secret.{storageaccountname}&quot;, f&quot;{secret}&quot;)<br>  spark.conf.set(f&quot;fs.azure.account.oauth2.client.endpoint.{storageaccountname}&quot;, f&quot;https://login.microsoftonline.com/{directoryid}/oauth2/token&quot;)</pre><p>The service principal used needs to be able to read from the $logs container. This is done by assigning the Storage Blob Data Reader role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*fila8oF_ZSbtO-6g5g22MQ.png" /><figcaption>Apply the Service Principal RBAC role</figcaption></figure><p>The prepared schema is then used to read and parse the semi-colon-separated log data. A temp view is created ready to crunch the data in SQL.</p><pre>logdata = spark.read.option(&quot;sep&quot;, &quot;;&quot;).schema(diagnosticLogRecordv2).csv(logpath)<br>logdata.createOrReplaceTempView(&quot;adlslogs&quot;)<br>display(logdata)</pre><p>We don’t want to load millions of records into Power BI and aggregate them there. We can employ a performant distributed processing engine like Spark to crunch the big data into summarized data.</p><pre>create or replace temporary view ContainerReadCount<br>as<br>select <br>  requestStartDate,<br>  requestYYMM,<br>  concat(dataset, &#39; (&#39;, storage_container, &#39;-&#39;, lakezone, &#39;)&#39; ) as container,<br>  userprincipal,<br>  count(1) as ReadFileCount<br>from <br>(<br>  select<br>    *,<br>    to_date(requeststarttime) as requestStartDate,<br>    left(getArgument(&#39;job_start_date&#39;), 7) as requestYYMM,<br>    split(requestedobjectkey, &#39;/&#39;)[2] as storage_container,<br>    split(requestedobjectkey, &#39;/&#39;)[3] as lakezone,<br>    split(requestedobjectkey, &#39;/&#39;)[4] as dataset,<br>    coalesce(userprincipalname,serviceprincalname,userobjectid) userprincipal<br>  from logs<br>) x<br>where operationtype = &#39;ReadFile&#39;<br>and split(requestedobjectkey, &#39;/&#39;)[2] NOT LIKE &quot;%logs%&quot;<br>group by requestStartDate, requestYYMM, container, userprincipal<br>order by requestStartDate</pre><p>The ‘requestedobjectkey’ exposes the path in the lake being accessed. This is then chopped up to create dataset labels for the dashboard.</p><p>I want to partition my output data by runtime-month, so partition values are created from the runtime date ‘job_start_date’ (requestYYMM)</p><p>The Microsoft documentation suggests that a user-friendly service principal name is available in the logs. In my experience, this is always null. However, when a user principal made the request the ‘userprincipalname’ is populated with a user-friendly identifier. For the case of service, principle reads, userobjectid ( the Azure GUID ) is substituted in. This GUID is crucial to discovering the friendly name once the data is in Power BI. It can be fed as a parameter into a ‘get’ call to the Microsoft Graph REST API.</p><p>Hence the following code…</p><pre>...<br>coalesce(userprincipalname,serviceprincalname,userobjectid) userprincipal<br>...</pre><p>The log data is then summarized by request start date, processing month, container (logical label) and user principal. Counting the read requests made.</p><p>Then it’s just a matter of writing the data generated by the view to partitions in the blob store.</p><pre>spark.conf.set(&quot;spark.sql.sources.partitionOverwriteMode&quot;,&quot;dynamic&quot;)<br>df = sqlContext.table(&quot;ContainerReadCount&quot;)<br><br>output_folder = &quot;abfss://adlslogprocessing@gsstorage.dfs.core.windows.net/ReadFileCountsV2/&quot;<br>df.repartition(1).write.partitionBy(&quot;requestYYMM&quot;).mode(&quot;overwrite&quot;).format(&quot;parquet&quot;).save(output_folder)</pre><h4>Microsoft Graph</h4><p>If you haven’t already done so, head on over to the Microsoft Graph Explorer, login ( assuming you already have an Azure account ) and try it out.</p><p><a href="https://developer.microsoft.com/en-us/graph/graph-explorer">Graph Explorer | Try Microsoft Graph APIs - Microsoft Graph</a></p><p>There are a ton of useful API end-points that could be utilised in so many operational scenarios.</p><p>For this dashboard, I used the following end-point…</p><p><a href="https://graph.microsoft.com/v1.0/servicePrincipals/%7BservicePrincipal-id">https://graph.microsoft.com/v1.0/servicePrincipals/{servicePrincipal-id</a>}</p><p>Power BI has a web connector that can be used to call REST APIs. With this connector, you can lookup the friendly name for the service principals for each serviceprincipalname ( servicePrincipal-id ) in the Data Lake diagnostic logs.</p><p>Here is the custom Power BI function I used to perform the lookup…</p><pre>= (params) =&gt;<br>let<br>    <br>    GetJsonQuery = Web.Contents(&quot;https://graph.microsoft.com/v1.0/servicePrincipals/&quot; &amp; params, [<br>            Headers = [Authorization=bearertoken]<br>        ]  ),<br>    FormatAsJsonQuery = Json.Document(GetJsonQuery),<br><br>    data = try FormatAsJsonQuery[appDisplayName] otherwise null,<br>    res = data<br>in<br>    res</pre><p>‘bearertoken’ is another query I use to obtain my bearer token to authorise the request to Microsoft Graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*nafXjRwSLDau6P0qo_KFyA.png" /><figcaption>Add a lookup column to get friendly principal names from Microsoft Graph</figcaption></figure><p>The function is invoked as a custom column on the dataset prepared by the Databricks notebook.</p><h3>Conclusion</h3><p>I deliberately didn’t want this to be a ten-page ‘build a power BI dashboard’ walkthrough. My intention was to cover the key points regarding visualising this rich source of information; the data lake diagnostic log.</p><p>Back to the narrative of the post, would humans decide it would be ‘ok’ to gobble up a vulnerable cola bottle or do something with data they probably shouldn’t be doing? If they knew that their actions were recorded and easily observable by their community maybe they would be more inclined to pause and consider the ‘right thing’. After all, I think doing the right thing really sits at the heart of a good data governance culture.</p><p>Finally, I wanted to show another way the same data is re-used to show individual user trends. This gives us great insight into who are the people within the organisation most active with the Enterprise data. Perhaps a conversation starter around understanding a workload, potentially leading to performance improvements like local caching for repeated reads. The more we understand how users interact with data the more empowering the technical solutions we can serve them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k_ZqZzJlpdIXHdXVVXQ-0A.png" /><figcaption>User consumption trends</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d1c947f2865" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/azure-data-lake-usage-monitoring-1d1c947f2865">Azure Data Lake Usage Monitoring</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-Products, Black Holes and a Washing Machine]]></title>
            <link>https://medium.com/analytics-vidhya/data-products-black-holes-and-a-washing-machine-5828b8a3e80f?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/5828b8a3e80f</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[enterprise-technology]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[data-as-a-product]]></category>
            <category><![CDATA[data-mesh]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 07:59:11 GMT</pubDate>
            <atom:updated>2022-07-29T20:12:35.469Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understand how the enterprise can build a tangible definition of Data Products. How can we make the necessary mindset shift to operate data as a product?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7-48e_n4AxPKH3kv9movg.jpeg" /><figcaption>Image source <a href="http://pixabay.com/">Pixabay.com</a></figcaption></figure><p>Black holes are incredibly mysterious and alluring to the curious mind. We know they are there not because we can see them or even imagine what they are. But because we can observe their effect on the universe.</p><blockquote>There are no black holes — in the sense of regimes from which light can’t escape to infinity. There are however apparent horizons which persist for a period of time.</blockquote><blockquote>Stephen Hawkins</blockquote><p>To the average Joe like myself, Stephen’s beautiful words are somewhat bemusing. For a while, I had the same curiosity and bemusement about data-products. Lots of people are talking about them and writing about them, so they must exist. But I can’t see them or visualise them, so what are they?</p><p>This time Stephen has some more comforting words for us.</p><blockquote>If you feel you are in a black hole. Don’t give up there’s a way out.</blockquote><blockquote>Stephen Hawkins</blockquote><p>Yes Stephen, I do feel in the dark when it comes to data-products. I want to find the way out.</p><h3>Data-Products</h3><p><a href="https://twitter.com/dpatil">DJ Patil</a>, former United States Chief Data Scientist, defined a data product as “a product that facilitates an end goal through the use of data”</p><p>Why didn’t my parents call me DJ? Such a cool name. I could have been a…no wait, that doesn’t work. Mr Patil offers a good succinct starting point. What else is out there?</p><p>Well, we must turn to the matriarch of the data-mesh, <a href="https://twitter.com/zhamakd">Zhamak Dehghani</a>. In her numerous words of wisdom, she bestows us with six facets of a data-product. Later summarized by <a href="https://svenbalnojan.medium.com/?source=post_page-----21bed87876f2--------------------------------">Sven Balnojan</a> as DATSIS in this <a href="https://towardsdatascience.com/data-mesh-applied-21bed87876f2">post</a>.</p><ul><li>Discoverable</li><li>Addressable</li><li>Trustworthy</li><li>Self-describing</li><li>Interoperable</li><li>Secure</li></ul><p>Great, we have a principle framework for defining a data-product.</p><h3>A Washing Machine</h3><p>Recently our trusty steed spun its last spin. It’s been a dedicated trooper for many a year, but it was finally time to rest. So when I started seeking a replacement, I thought about that important term ‘data as an asset, aka data as a product” and how this relates to any product.</p><h4>Discoverable</h4><p>I needed a portal to discover the Washing Machine of my dreams. I needed search capabilities and some high-level information covering the most important properties of the product. Search and properties were the ingredients I needed to make a decision if the washing machine was right for me.</p><h4>Addressable</h4><p>The washing machine&#39;s dimensions, power rating and loading method told me that it would work within my existing kitchen infrastructure, style and laundry processes. Once home I could access all its features without friction.</p><h4>Trustworthy</h4><p>Well, well, it had a 4.5 star rating from other consumers, and it was sold by a reputable manufacturer with a five-year warranty.</p><p>This product’s going in the basket, time to checkout.</p><h4>Self-describing</h4><p>Once home, the packaging explained there was a washing machine inside and how to access it. The documentation shipped with the appliance explained all the details related to the product.</p><h4>Interoperable</h4><p>I operate the functions of the machine both through in-built controls and remotely via the home wi-fi. The quick-start guide made this an easier experience.</p><h4>Secure</h4><p>Can you get that door open before it’s good and ready for you to open it? Not a chance, you’ll need to wait patiently.</p><p>Now I’ve made some careful observations about the new appliance in my life, can I turn this product understanding into data-product understanding.</p><h4>Digital Data-Product Contract</h4><p>If we want the enterprise to understand and love data-products we can’t give them an enigma. We must give them something they can see and touch.</p><p>No more conceptual thinking or theory, let&#39;s get real. So is a data-product a file, dataset, OData, Graph or Cognitive Service API? Is it a data-warehouse star schema, BI datamart, ML model or NoSQL DB? If we recall DJ Patil’s principal statement, it can be any of these things. The first lesson we must understand is that data-products can come in many types. Just as we have many home appliances to suit all our needs.</p><p>Our enterprise data-product definition itself must be interoperable so we can weaver it into the fabric of our data governance. We must produce a meta-data artefact. A Digital Data-Product Contract.</p><p>Open API standards provide a very good blueprint for organisation information as a programmatically addressable artefact. I’ll use YAML to describe a logical Digital Data-Product Contract. I’m not advocating the use of Open API standards or YAML here, that would be a whole other post. But simply utilising them to create an example. Other methods of digitally defining a Data-Product are plausible.</p><p><strong>Example Digital Data-Product Contract</strong></p><p>There is a lot going on in this YAML contract. So I’ll highlight some of the important elements and how they relate to the DATSIS convention.</p><pre>--- <br>dependencies: <br>  - <br>    info: <br>      contact: <br>        email: <a href="/service/mailto:pimteam@myorg.com">pimteam@myorg.com</a><br>        url: &quot;<a href="https://myorg.com/pimwiki.html">https://myorg.com/pimwiki.html</a>&quot;<br>      description: &quot;Data for this product is sourced from the Product Identification Management service.&quot;<br>      termsOfService: &quot;<a href="https://myorg.com/pimwiki/sitereliability.html">https://myorg.com/pimwiki/sitereliability.html</a>&quot;<br>      title: &quot;PIM Service&quot;<br>      version: &quot;2.1.0&quot;<br>      cadence: &quot;Hourly&quot;<br>      provenanceLineage: &quot;<a href="https://myorg.com/pimwiki/lineage.html">https://myorg.com/pimwiki/lineage.html</a>&quot;<br>  - <br>    info: <br>      contact: <br>        email: <a href="/service/mailto:ordersteam@myorg.com">ordersteam@myorg.com</a><br>        url: &quot;<a href="https://myorg.com/orderswiki.html">https://myorg.com/orderswiki.html</a>&quot;<br>      description: &quot;Data for e-commerce orders is sourced from the Order Management service.&quot;<br>      termsOfService: &quot;<a href="https://myorg.com/orderswiki/sitereliability.html">https://myorg.com/orderswiki/sitereliability.html</a>&quot;<br>      title: &quot;Orders Service&quot;<br>      version: &quot;1.5.0&quot;<br>      cadence: &quot;Continuous&quot;<br>      provenanceLineage: &quot;<a href="https://myorg.com/pimwiki/lineage.html">https://myorg.com/ordermanagementwiki/lineage.html</a>&quot;<br>info: <br>  contact: <br>    email: <a href="/service/mailto:product360team@myorg.com">product360team@myorg.com</a><br>    url: &quot;<a href="https://myorg.com/product360wiki.html">https://myorg.com/product360wiki.html</a>&quot;<br>  description: &quot;A universal perspective of products transacted by the organisation.&quot;<br>  termsOfService: &quot;<a href="https://myorg.com/product360wiki/sitereliability.html">https://myorg.com/product360wiki/sitereliability.html</a>&quot;<br>  title: &quot;Product 360 Foundation Data Product&quot;<br>  version: &quot;1.0.0&quot;<br>  type: &quot;Deltalake Dataset&quot;<br>  location: &quot;lakeprotocol://productdomain/product360&quot;<br>  gettingStartedGuide: &quot;<a href="https://myorg.com/product360basicinterop-notebook.html">https://myorg.com/product360basicinterop-notebook.html</a>&quot;<br>  accessrequestprocess: &quot;<a href="https://myorg.com/product360accessrequestform.html">https://myorg.com/product360accessrequestform.html</a>&quot;<br>  <br>  schema:<br>    title: &quot;Product 360 Data Schema&quot;<br>    schemaversion: &quot;1.0.0&quot;<br>    type: object<br>    properties:<br>      productid:<br>        type: string<br>        format: uuid<br>      statefulperiod:<br>        type: string<br>        format: datatime<br>      productname:<br>        type: string<br>      productperformancescore:<br>        type: float<br>    keying:<br>      -<br>        property: productid<br>        description: &quot;The productid is part of the composite key that uniquely identifies a record.&quot;<br>      -<br>        property: statefulperiod<br>        description: &quot;The productid and statefulperiod uniquely identifies a products performance score within a bounded or unbounded period.&quot;<br>    sequencing:<br>      -<br>        property: statefulperiod<br>        description: &quot;The statefulperiod is a series of adjacent periods of time without gaps. The series spans the very first time a data-point was established until now. Each period is punctated by the eventime of any source dependency data changes.&quot;<br>  certifcation:<br>    informationclassification: &quot;Commercially sensitive&quot;<br>    datatreaments:<br>      -<br>        greateexpectationstest: &quot;Result (56/56) passed&quot;<br>        version: &quot;3.1&quot;<br>        lastrundatetime: &quot;15/07/22&quot;<br>      -<br>        dataanomoloydetectionframework: &quot;All data-points within expected tolerances.&quot;<br>        version: &quot;2.0&quot;<br>        lastrundatetime: &quot;15/07/22&quot;<br>dependants:<br>  - <br>    info: <br>      contact: <br>        email: <a href="/service/mailto:appliancegrowthanddevelopmentteam@myorg.com">appliancegrowthanddevelopmentteam@myorg.com</a><br>        url: &quot;<a href="https://myorg.com/appliancedevelopmentwiki.html">https://myorg.com/appliancedevelopmentwiki.html</a>&quot;<br>      description: &quot;The appliance commercial growth and development team use.&quot;<br>      title: &quot;The Appliance Growth and Development BI Dashboard&quot;<br>      version: &quot;3.1.0&quot;<br>      cadence: &quot;4 hours&quot;<br>      provenanceLineage: &quot;<a href="https://myorg.com/appliancedevelopmentwiki/lineage.html">https://myorg.com/appliancedevelopmentwiki/lineage.html</a>&quot;<br>  - <br>    info: <br>      contact: <br>        email: <a href="/service/mailto:tradingoptimisationteam@myorg.com">tradingoptimisationteam@myorg.com</a><br>        url: &quot;<a href="https://myorg.com/tradingoptimiserwiki.html">https://myorg.com/tradingoptimiserwiki.html</a>&quot;<br>      description: &quot;The trading optimisation use this data-product and other data-products to optimise sales revenues.&quot;<br>      termsOfService: &quot;<a href="https://myorg.com/tradingoptimiserwiki/sitereliability.html">https://myorg.com/tradingoptimiserwiki/sitereliability.html</a>&quot;<br>      title: &quot;Trading Optimiser&quot;<br>      version: &quot;1.5.0&quot;<br>      cadence: &quot;Continuous&quot;<br>      provenanceLineage: &quot;<a href="https://myorg.com/tradingoptimiserwiki/lineage.html">https://myorg.com/tradingoptimiserwiki/lineage.html</a>&quot;</pre><h4>Discoverable</h4><p>This digital information can easily be utilised in indexing and searching technologies. The kind of tech you’ll find in the array of data governance tools on the market. The information is summarised, giving the explorer enough information to quickly form an understanding of the product. However, more detailed information is also available through hyperlinks allowing the explorer to ensure the product meets their needs.</p><h4>Addressable</h4><p>The contact, version, type and location information help me understand where and how the data resides.</p><pre>info: <br>  contact: <br>    email: <a href="/service/mailto:product360team@myorg.com">product360team@myorg.com</a><br>    url: &quot;<a href="https://myorg.com/product360wiki.html">https://myorg.com/product360wiki.html</a>&quot;<br>  version: &quot;1.0.0&quot;<br>  type: &quot;Deltalake Dataset&quot;<br>  location: &quot;lakeprotocol://productdomain/product360&quot;</pre><h4>Trustworthy</h4><p>The lineage, terms of service, dependencies and data treatment information generate tangible evidence that instils trust in data-product consumers.</p><pre>--- <br>dependencies: <br>  - <br>    info: <br>      cadence: Hourly<br>      contact: <br>        email: <a href="/service/mailto:pimteam@myorg.com">pimteam@myorg.com</a><br>        url: &quot;<a href="https://myorg.com/pimwiki.html">https://myorg.com/pimwiki.html</a>&quot;<br>      description: &quot;Data for this product is sourced from the Product Identification Management service.&quot;<br>      provenanceLineage: &quot;<a href="https://myorg.com/pimwiki/lineage.html">https://myorg.com/pimwiki/lineage.html</a>&quot;<br>      termsOfService: &quot;<a href="https://myorg.com/pimwiki/sitereliability.html">https://myorg.com/pimwiki/sitereliability.html</a>&quot;<br>      title: &quot;PIM Service&quot;<br>      version: &quot;2.1.0&quot;<br>info: <br>  certifcation: <br>    datatreaments: <br>      - <br>        greateexpectationstest: &quot;Result (56/56) passed&quot;<br>        lastrundatetime: 15/07/22<br>        version: &quot;3.1&quot;<br>      - <br>        dataanomoloydetectionframework: &quot;All data-points within expected tolerances.&quot;<br>        lastrundatetime: 15/07/22<br>        version: &quot;2.0&quot;<br>    informationclassification: &quot;Commercially sensitive&quot;<br>  contact: <br>    email: <a href="/service/mailto:product360team@myorg.com">product360team@myorg.com</a><br>    url: &quot;<a href="https://myorg.com/product360wiki.html">https://myorg.com/product360wiki.html</a>&quot;<br>  description: &quot;A universal perspective of products transacted by the organisation.&quot;<br>  termsOfService: &quot;<a href="https://myorg.com/product360wiki/sitereliability.html">https://myorg.com/product360wiki/sitereliability.html</a>&quot;</pre><h4>Self-describing</h4><p>The compound effect of defining the various elements of the digital contract means that the product can be intuitively used. There should be no need for excessive data familiarisation.</p><h4>Interoperable</h4><p>The access request process, schema info, and getting started guides mean that consumers can interact with the data-product without friction.</p><pre>info: <br>  accessrequestprocess: &quot;<a href="https://myorg.com/product360accessrequestform.html">https://myorg.com/product360accessrequestform.html</a>&quot;<br>  gettingStartedGuide: &quot;<a href="https://myorg.com/product360basicinterop-notebook.html">https://myorg.com/product360basicinterop-notebook.html</a>&quot;<br>  schema: <br>    keying: <br>      - <br>        description: &quot;The productid is part of the composite key that uniquely identifies a record.&quot;<br>        property: productid<br>      - <br>        description: &quot;The productid and statefulperiod uniquely identifies a products performance score within a bounded or unbounded period.&quot;<br>        property: statefulperiod<br>    properties: <br>      productid: <br>        format: uuid<br>        type: string<br>      productname: <br>        type: string<br>      productperformancescore: <br>        type: float<br>      statefulperiod: <br>        format: datatime<br>        type: string<br>    schemaversion: &quot;1.0.0&quot;<br>    sequencing: <br>      - <br>        description: &quot;The statefulperiod is a series of adjacent periods of time without gaps. The series spans the very first time a data-point was established until now. Each period is punctated by the eventime of any source dependency data changes.&quot;<br>        property: statefulperiod<br>    title: &quot;Product 360 Data Schema&quot;<br>    type: object</pre><h4>Secure</h4><p>The information classification and access request process information demonstrates the product is secure and ready for responsible use. Secure not imprisoned. Defining security measures that don’t expose access control processes means the data is locked away. The organisation then fails to capitalise on the information value.</p><pre>info:<br> informationclassification: &quot;Commercially sensitive&quot; <br> accessrequestprocess: &quot;<a href="https://myorg.com/product360accessrequestform.html">https://myorg.com/product360accessrequestform.html</a>&quot;</pre><h3>Closing Thoughts</h3><p>It’s been a while since I wrote anything so this has been a joy to ink. If you came this far down the page I also hope you have enjoyed the content.</p><p>My main objective was to demystify the Data-Product. If I have achieved that, then awesome. If I have ignited conversation within your technical communities then that&#39;s even better.</p><p>I’d like to pay thanks to two other writers and encourage you to peruse their work. I’ve learnt a lot from their musing.</p><p>Piethein Strengholt: <a href="https://piethein.medium.com/">https://piethein.medium.com/</a></p><p>Eric Broda: <a href="https://medium.com/@ericbroda">https://medium.com/@ericbroda</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5828b8a3e80f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/data-products-black-holes-and-a-washing-machine-5828b8a3e80f">Data-Products, Black Holes and a Washing Machine</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GAVRO — Managed Big-Data Schema Evolution]]></title>
            <link>https://medium.com/data-science/gavro-managed-big-data-schema-evolution-8217431f278f?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/8217431f278f</guid>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[avro]]></category>
            <category><![CDATA[azure-event-hub]]></category>
            <category><![CDATA[azure-databricks]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Mon, 11 May 2020 00:03:25 GMT</pubDate>
            <atom:updated>2020-05-11T00:03:25.017Z</atom:updated>
            <content:encoded><![CDATA[<h3>GAVRO — Managed Big Data Schema Evolution</h3><h4>Wouldn’t it be great to build a data ingestion architecture that was resilient to change? More specifically, resilient to schema evolution.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0UuaIMUUNXTQjDcBR2WuZQ.png" /><figcaption>Image source <a href="http://pixabay.com/">Pixabay.com</a></figcaption></figure><p>Managing schema changes has always proved troublesome for architects and software engineers. Building a big-data platform is no different and managing schema evolution is still a challenge that needs solving. NoSQL, Hadoop and the schema-on-read mantra have gone some way towards alleviating the trappings of strict schema enforcement. However, integration developers, analysts and data scientists are still hindered by the amount of data wrangling they need to perform when extracting accurate insights from big-data.</p><p>Successful business’ grow and evolve at pace accelerating and amplifying the volatility of known data schemas. Datasets are not static and constantly evolving, so knowing what business-fact data represents in the current and historical periods of the business is crucial to making confident information insights.</p><p>Through this article and accompanying GitHub <a href="https://github.com/GaryStrange/GAVRO">repo</a>, I’ll demonstrate how you can manage schema evolution in a big-data platform using Microsoft Azure technologies.</p><blockquote>This is an area that tends to be overlooked in practice until you run into your first production issues. Without thinking through data management and schema evolution carefully, people often pay a much higher cost later on.</blockquote><blockquote>Confluent.io (29th April 2020), Schema Evolution and Compatibility. <a href="https://docs.confluent.io/current/schema-registry/avro.html#schema-evolution-and-compatibility">https://docs.confluent.io/current/schema-registry/avro.html#schema-evolution-and-compatibility</a></blockquote><p>As a writer, it&#39;s difficult to decide how to tell your story. Do I jump straight into the technical solution to satisfy the engineers looking for succinct examples or do I start with the why’s and motivations? So I’ll leave it up to the reader. If you want to jump straight into the technical example head to the <a href="https://github.com/GaryStrange/GAVRO/blob/master/README.md">GitHub repo</a>. If you want the finer details, read on…</p><h3>Schema Management</h3><p>Serializing data to be stored in files to be analysed later, is fairly straight forward if consumers understand the schema that was used to write the data and the schema never changes.</p><p>But what happens if the schema evolves over time? It becomes a little more complicated.</p><p>When the write-schema evolves due to a new business requirement, consumers (readers) must understand when the new schema was introduced and the definition of the new schema to successfully de-serialize the data. Failure to comprehend the schema-change event will impact data processing pipelines and services will error as they fail to de-serialize the data.</p><p>There are a few solutions to this problem… (this is by no means an exhaustive list).</p><p><strong>Release Co-ordination</strong></p><p>The writer and the reader coordinate their backlogs and software releases. This may work well when the writer and the reader applications are developed and maintained by the same engineering team. However, it’s often the case that the writer and reader are working to different objectives and priorities across the enterprise. Temporally coupling independent team backlogs through strict interface dependencies is to be avoided as it inhibits agility and delivery velocity.</p><p><strong>Schema Version Management</strong></p><p>Versioning write-schemas enables forward and backwards compatibility management. Providing forward and backward compatibility de-couples backlogs and priorities, allowing engineering teams independent progression of their goals.</p><p>Versioning is generally discussed in the context of two distinct sub-topics.</p><p>Major — A major version change typically breaks interfaces and contracts between systems. A major schema change would typically inhibit readers from reading the data written by the new schema version. Forward and backward compatibility is difficult or impossible.</p><p>Minor — A minor version change is typically considered to be a low impact change. Forward and backward compatibility is often possible. Readers typically continue to operate as they previously did, successfully de-serialising data without progressing to the newest version of the schema.</p><p>Wouldn’t it be nice to build a data ingestion architecture that had some resilience to change? More specifically, resilience to schema evolution.</p><p>Below is the Azure architecture I’ll use to describe how schema evolution can be managed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*qYae130ca741J2CRBVvIkw.png" /></figure><h3>Schema Registry</h3><p>Kafka’s Schema Registry provides a great example of managing schema evolution over streaming architecture. Azure Event Hubs, Microsoft’s Kafka like product, doesn’t currently have a schema registry feature. Events published to Event Hubs are serialised into a binary blob nested in the body of Event Hubs Avro schema (Fig.1). We will get into the details shortly, but essentially the published event data is schema-less, any down-stream readers need to de-serialise the binary blob by asserting a schema at read time. There are some clever-work-arounds¹ that utilise Confluent’s schema-registry alongside Event Hubs. I will build on these suggestions and provide an alternative approach to schema evolution resilience. In my previous story (<a href="https://medium.com/@gary.strange/evolving-into-a-big-data-driven-business-in-the-azure-cloud-data-ingestion-65bc8b659570?source=your_stories_page---------------------------">Evolving into a Big-Data Driven Business in the Azure Cloud: Data Ingestion</a>), I described a Data Lake ingestion architecture that utilises Event Hubs and Event Hub Capture to form a batch layer for big data analytics. I’ll use this architecture as reference for handling schema evolution.</p><blockquote>Figure 1.</blockquote><pre>{</pre><pre>&quot;type&quot;:&quot;record&quot;,<br>    &quot;name&quot;:&quot;EventData&quot;,<br>    &quot;namespace&quot;:&quot;Microsoft.ServiceBus.Messaging&quot;,<br>    &quot;fields&quot;:[<br>                 {&quot;name&quot;:&quot;SequenceNumber&quot;,&quot;type&quot;:&quot;long&quot;},<br>                 {&quot;name&quot;:&quot;Offset&quot;,&quot;type&quot;:&quot;string&quot;},<br>                 {&quot;name&quot;:&quot;EnqueuedTimeUtc&quot;,&quot;type&quot;:&quot;string&quot;},<br>                 {&quot;name&quot;:&quot;SystemProperties&quot;,&quot;type&quot;:{&quot;type&quot;:&quot;map&quot;,&quot;values&quot;:[&quot;long&quot;,&quot;double&quot;,&quot;string&quot;,&quot;bytes&quot;]}},<br>                 {&quot;name&quot;:&quot;Properties&quot;,&quot;type&quot;:{&quot;type&quot;:&quot;map&quot;,&quot;values&quot;:[&quot;long&quot;,&quot;double&quot;,&quot;string&quot;,&quot;bytes&quot;]}},<br>                 {&quot;name&quot;:&quot;<strong>Body</strong>&quot;,&quot;type&quot;:[&quot;null&quot;,&quot;bytes&quot;]}<br>             ]<br>}</pre><p><strong>Event Hubs</strong></p><p>How many? How many Event Hubs should I have? Or to put it another way, should I have one big pipe for all my data or many smaller pipes for each message type? The same question has been asked regarding Kafka topics and there is no definitive answer². One thing is highly probably, different use cases will favour different approaches. If your concern is just to get messages from A to B or you’re integrating with architecture outside of your control, messages might flow through one Event Hub, one big pipe. If some of your data is highly sensitive and you only want certain subscribers to read and process that data or you may need specific partition strategies which would lead to the adoption of many event hubs within a namespace, many smaller pipes.</p><p>Big Pipe</p><ul><li>If an Event Hub contains many message types with varying schemas how would we identify and deserialize the various messages correctly?</li></ul><p>Small Pipe</p><ul><li>When an Event Hub contains just one message type and that message type evolves over time how do consumers deserialize the new versions of the message?</li></ul><p>At first glance, these issues may seem to be unrelated. However, they are manifestations of the same core problem. How to manage the de-serialisation of data.</p><p>All messages on Event Hubs are anonymous blobs of binary. One option would be for consumers to infer the schema. However, this approach is non-deterministic and based on sampling, so the inferred schema can only be an approximation. Another approach might be to assert the schema on consumption. However, this means that engineering teams consuming messages are temporarily coupled to the evolution of the schema, even for minor changes. Event Hub Capture offers us an opportunity to break the temporal coupling and allow consumers to consume data from t0** at their own pace. However, if a consumer wants to read and make use of all the AVRO files, produced by the Event Hub Capture process, they will also need to know which write schemas were used to write the binary messages over the period that the events were captured. This could be many months or even years of data. As a consumer, I would need to know the schema evolution time-line or I will struggle to make use of the data.</p><p><em>** well at least from the begging of the Event Hub capture configuration.</em></p><p>Early impressions of Event Hub Capture might lead you to believe that AVRO was being used to help address the concerns detailed above. However, after reading the <a href="https://avro.apache.org/docs/current/spec.html">AVRO specification</a> it would seem that only minor version changes are possible. So breaking changes cannot be managed and AVRO files with multiple message types would be impossible.</p><p>Event Hubs allow us to add additional metadata when we publish messages. This metadata is the key to managing schema evolution.</p><p>There are two possible options.</p><p>1) The write-schema is stored with each message in the Event Hub client properties dictionary. This would severely inflate the storage costs.</p><p>2) A message type identifier is stored in the Event Hub client properties dictionary. The identifier is then used to lookup the schema from a central store.</p><p>With both of these solutions, the schema is always directly or indirectly stored with the data. The files produced by Event Hub Capture will always have a means of identifying the write schema. Moreover, each file can contain x number of message types and y number of message versions.</p><p>Let’s take a look at an Azure Function that publishes messages to Event Hub using the client SDK.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45483e585962d12aed02407fd6ba49fe/href">https://medium.com/media/45483e585962d12aed02407fd6ba49fe/href</a></iframe><p>The schema identifier is always stored alongside the data (line 17).</p><h3>Azure Function</h3><p>In the example above, the function uses a timer trigger to execute new instances of the function every 5 seconds. The function trigger is irrelevant, and it could easily be a CosmosDB Change Feed Processing binding or any other bindings that produce data to be processed. Moreover, using a function app is also irrelevant, what matters is what you publish to the Event Hub. The function app lends itself to a succinct example.</p><p>It&#39;s important to note the schema version of the message is being persisted alongside the message by adding a reference to eventData.Properties. This metadata attribution is critical when it comes to reading the data at a later date. When events are published to Event Hub the schema identifier is always stored alongside the data.</p><h4>Event Hub Capture</h4><p>I configure Event Hub Capture to produce a new AVRO file every minute or every 500mb, whichever comes first. So, we now have the schema identifier and data captured in neatly partitioned AVRO files, but how do we process it in our big data pipelines. In my previous story, I covered the subject of maintaining a schema repository to capture a truthful account of all the enterprise&#39;s schemas. This repo is used to create an artefact that will be consumed in the data processing pipeline. The artefact is a simple key-value store connecting versioned schema identifiers with the write schema used. For the purpose of this document, I’ll use a simple Databrick Python notebook to process the AVRO data.</p><h3>Databricks — Notebook</h3><p>I won’t go into a full description of the complete notebook but focus on the most important cells (the complete notebook is in the GitHub repo).</p><h4>AVRO Deserialisation</h4><p>The first is the reading of the Event Hub Data Capture AVRO. Spark’s AVRO dataframeReader is used to read AVRO files from storage and de-serialise them into a data-frame. We can allow Spark to infer the schema at this point as we know it to be non-volatile (i.e. the Azure Event Hub schema). The properties attribute holds the information about the schema version that was used to write the data in the binary field ‘Body’. A simple projection is run over the data to process a refined data-frame with three columns. The schema version is extracted from the properties object (the stored value from the serialised properties dictionary is stored in the child attribute member2). The ‘Body’ attribute is cast to a string as we want to use spark’s JSON de-serialiser on it later in the notebook.</p><pre><strong>from</strong> pyspark.sql.functions <strong>import</strong> col</pre><pre>rawAvroDf = spark.read.format(&quot;avro&quot;).load(&quot;wasbs://&quot; + containerName + &quot;@&quot; + storageAccName + &quot;.blob.core.windows.net/gavroehnamespace/gavroeh/*/2020/*/*/*/*/*.avro&quot;)</pre><pre>avroDf = rawAvroDf.select(col(&quot;Properties.SchemaVersion.member2&quot;).alias(&#39;SchemaVersion&#39;), col(&quot;Body&quot;).cast(&quot;string&quot;))</pre><pre>display(avroDf)</pre><h4>Schema Lookup</h4><p>The second is the schema lookup object. For the purpose of simplifying the example, I’m manually creating some schemas that will be used to deserialise the AVRO data. However, in practice, these schema’s will be generated from a schema repository and be stored as runtime artefacts. Note to self, need to write this up as a follow-up article.</p><p>The schemas, stored in a one-dimensional array, represent an entity that has evolved. In this theoretical example, the business has grown and started trading overseas in new currencies. Transactions now need currency identifiers, so a new attribute ‘Currency’ was added to the sales-order data schema. As readers, we need to be able to de-serialise the new data successfully.</p><pre><strong>from</strong> pyspark.sql.types <strong>import</strong> StructType, StructField, LongType, StringType, ArrayType, DoubleType</pre><pre>salesOrderV1 =StructType([StructField(&#39;OrderId&#39;,StringType(),<strong>True</strong>),StructField(&#39;OrderAmount&#39;,DoubleType(),<strong>True</strong>),StructField(&#39;OrderCreatedUTC&#39;,StringType(),<strong>True</strong>)])</pre><pre>salesOrderV2 =StructType([StructField(&#39;OrderId&#39;,StringType(),<strong>True</strong>),StructField(&#39;OrderAmount&#39;,DoubleType(),<strong>True</strong>),StructField(&#39;Currency&#39;,StringType(),<strong>False</strong>),StructField(&#39;OrderCreatedUTC&#39;,StringType(),<strong>True</strong>)])</pre><pre>salesOrderSchemaDictionary = { &quot;v1.0&quot;:salesOrderV1, &quot;v2.0&quot;:salesOrderV2 }</pre><pre>salesOrderSchemaDictionary</pre><h4>JSON Deserialisation</h4><p>The third cell I’d like to focus on is the cell that actually reads and de-serialises the data. The Event Hub Data Capture output that was read into a data-frame previously is used to determine a distinct list of schema versions present in the data. For each schema version, a new temporary SparkSQL table will be created to access the de-serialised data. The original AVRO data-frame is filtered on each iteration of the ‘for’ loop, grouping records by distinct schema-version to produce subsets of data. Each subset is then de-serialised using the corresponding schema in the salesOrderSchemaDictionary. A number of new temporary tables will be created and the output of this cell will display a list of created objects.</p><pre><strong>from</strong> pyspark.sql.functions <strong>import</strong> concat, lit, regexp_replace</pre><pre>distinctSchemaVersions = avroDf.select(&#39;SchemaVersion&#39;).distinct()</pre><pre>objectToCreate = distinctSchemaVersions.withColumn(&#39;TableName&#39;, concat(lit(&#39;SalesOrder&#39;),regexp_replace(col(&#39;SchemaVersion&#39;), &#39;[.]&#39;, &#39;_&#39;))).collect()</pre><pre>display(objectToCreate)</pre><pre><strong>for</strong> record <strong>in</strong> objectToCreate:</pre><pre>schemaVersion = record.SchemaVersion</pre><pre>jsonRdd = avroDf.filter(col(&quot;SchemaVersion&quot;) == schemaVersion).select(avroDf.Body)</pre><pre>objectJson = jsonRdd.rdd.map(<strong>lambda</strong> x: x[0])</pre><pre>dataExtract = spark.read.schema(salesOrderSchemaDictionary[schemaVersion]).json(objectJson)</pre><pre>dataExtract.registerTempTable(record.TableName)</pre><h4>Finally</h4><p>Finally, SparkSQL can be used to explore the successful deserialised data in the temporary tables.</p><pre>%sql<br><strong>select</strong> * <strong>from</strong> SalesOrderv1_0</pre><pre>%sql<br><strong>select</strong> * <strong>from</strong> SalesOrderv2_0</pre><h3>Conclusion</h3><p>I should have started by clearing up what GAVRO is. Sorry to disappoint, but it’s not some new Apache incubator project that you wasn’t aware of. It’s an endearing name that my colleagues gave to the method I described in this article. I believe it’s a combination of my first initial and AVRO, at first I found their nickname for the method to be a product of the team&#39;s camaraderie, but then it stuck.</p><p>I don’t believe in designing and prescribing methods that are completely exact and should be unconditionally applied to every enterprise because every enterprise is different. So if you take anything away from reading this then I hope it’s the motivation to think about the connotations of badly managed schema evolution within your big data pipe-lines. We hear time and time again about the struggles organisation’s have with extracting information and actionable insight from big-data and how expensive data-scientists are wasting 80% of their time wrestling with data preparation. Schema management is a weapon when applied properly, that can be used to accelerate data understanding and reduce time to insight. So take the time to invest in it and you will reap healthy returns.</p><h4>Citations</h4><p>[1] Volkan Civelek, Schema validation with Event Hubs (1st April 2019), <a href="https://azure.microsoft.com/en-gb/blog/schema-validation-with-event-hubs/">https://azure.microsoft.com/en-gb/blog/schema-validation-with-event-hubs/</a></p><p>[2] Martin Kleppman, Should you put several event types in the same Kafka topic?(18th Jan 2018), <a href="https://martin.kleppmann.com/2018/01/18/event-types-in-kafka-topic.html">https://martin.kleppmann.com/2018/01/18/event-types-in-kafka-topic.html</a></p><h4>Influences</h4><p>Yahoo’s Apache Pulsar System: <a href="https://pulsar.apache.org/docs/en/schema-evolution-compatibility/">https://pulsar.apache.org/docs/en/schema-evolution-compatibility/</a></p><p>Confluent.io’s Schema-Registry: <a href="https://docs.confluent.io/current/schema-registry/index.html">https://docs.confluent.io/current/schema-registry/index.html</a></p><p>Jay Kreps, The Log: What every software engineer should know about real-time data’s unifying abstraction (16th Dec 2013), <a href="https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying">https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8217431f278f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/gavro-managed-big-data-schema-evolution-8217431f278f">GAVRO — Managed Big-Data Schema Evolution</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolving into a Big-Data Driven Business in the Azure Cloud: Data Ingestion]]></title>
            <link>https://medium.com/@gary.strange/evolving-into-a-big-data-driven-business-in-the-azure-cloud-data-ingestion-65bc8b659570?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/65bc8b659570</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[azure-event-hub]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data-driven]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 12:19:36 GMT</pubDate>
            <atom:updated>2019-12-06T16:38:27.355Z</atom:updated>
            <content:encoded><![CDATA[<p>Previously, in <a href="https://medium.com/@gary.strange/evolving-into-a-big-data-driven-business-in-the-azure-cloud-part-i-b89a2c971e32">part one</a>, I covered a lot of the topics that I hope demonstrate why it’s difficult to build a Data Lake and become a big-data-driven organisation. Now its time to discuss how a data lake can be built-in Azure.</p><p>Throughout this article, I’ll use an eCommerce purchase processing architecture as a use case to give the following subject matter context.</p><p>Image 1: Simplified architecture, order processing service hosted in cloud service or Kubernetes container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*lTOtMVU1XE1AL9UW4ApM7Q.png" /></figure><ol><li>A customer places an order; The orders service records the order information and publishes a message. Both the payments service and stock service are subscribers of the orders messages.</li><li>Having seen the new order message the payment service will validate and process the financial transaction. On success, the payment service publishes a payment success message. The stock service subscribes to the payment messages.</li><li>The stock service will reserve stock when receiving the order message and allocate stock when receiving the payments message. The service will handle out-of-order messaging stopping reservation superseding allocations. On successful allocation of stock, a message is published. The orders service subscribes to the stock messages and updates the order accordingly.</li></ol><h4>Schema information capture</h4><p>A crucial aspect of building the Data Lake and making all the enterprises’ data available, is discovering and ingesting data from sources. Without reliable truthful data, the lake integrity is lost and consumers cannot build confident data insights. From the source teams, we must extract an understanding of their data structures (schema) and the end-points we will need to integrate with. The fruits of this metadata gathering exercise are then used to ingest data into the lake and publish reliable documentation to a meta-store and or data catalogue. With experience I’ve found that there is little consistency across the enterprise, some teams will maintain a word document, others a swagger specification, some might use a wiki and some just won’t have bothered at all. There will also be varying levels of accuracy as keeping metadata/documentation in sync is notoriously difficult and always at the lower end of decision-makers priorities. A more robust and reliable way of capturing this metadata from the various sources is to maintain a centralised git repository. A method that I believe started with the open-source community, it’s now commonplace to use a source control system like git to also maintain documentation, aligning the tools and disciplines used to develop code with the creation of documentation and metadata. JSON messages reign supreme in the micro-services world and therefore it makes sense to specify our in-bound data schemas with <a href="https://json-schema.org/">JSON schema</a> specifications. Once a source-team has submitted a Pull Request with the most up-to-date version of their schemas, validation tests can be run using a <a href="https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops#build-validation">build validation policy</a>. This gives the source-team immediate feedback on the accuracy of the schema and metadata they are submitting. It also enables the custodians of the Data Lake to automatically produce artefacts that enable automated ingestion of data. For example, the source JSON schema can be used to produce <a href="https://spark.apache.org/docs/2.2.1/api/java/org/apache/spark/sql/types/StructType.html">Scala</a> or <a href="https://spark.apache.org/docs/1.1.0/api/python/pyspark.sql.StructType-class.html">Pyspark </a>StructTypes to be consumed when reading the source data into a Spark ELT pipeline.</p><h3>Architecture</h3><h4>In-bound</h4><p>In my experience, the most challenging aspect of ingesting data into a Data Lake isn’t the ingestion part. It’s the extraction of data from the source. With n number of teams creating and managing n number of data producing services its difficult to align them all to one publishing pattern. Multiple are required. In the Azure world, three main options stand out, publish full-fat messages to an Azure Service Bus (ASB), publish full-fat messages to an Event Hub or exact bulk volumes of data to Blob storage. There is also the option of publishing events to an ASB or Event Hub, only then to make a call back to the source API. This approach struggles with separating the concerns of publishing data for analytics and delivering a resilient and responsive API for business-critical operations. As the services API workload increases, more events are produced, increasing the call-backs for data, thus further increasing the load on the services APIs.</p><p>As I mentioned we can also publish data from a source system by bulk loading into Blob at a regular interval. This approach is only suitable for source systems that are able to achieve bulk extract without impacting the BAU workload or legacy systems that don’t have the capability to publish full-fat messages. With this approach, there is no possibility of introducing a speed layer and real-time analytics. However, if its simplicity you favour this is the pattern to be used. For that reason, it shouldn’t be dismissed and is appropriate in some use cases.</p><p>The next option is ASB, if the source systems are in the Azure cloud then its highly likely that they’ll already be using ASB to transfer high-value enterprise message between systems. With the infrastructure already established, creating new topics and subscriptions that can be used to ingest data into the lake is trivial. This low overhead extension of existing infrastructure makes this pattern very appealing. However, again it doesn’t enable a speed layer. You also have to understand how service interruption and dead-lettering may impact the source systems SLAs.</p><p>Lastly, we have Event Hubs, if you’re familiar with Kafka or at least the commit log pattern, Event Hubs is an Azure PaaS offering. Using Event Hubs we can implement a pub/sub pattern where subscribers (consumers in the Event Hub world) maintain a position in the immutable commit log. Before we dive into the unique facets of Event Hub we should first understand where it sits in the database and messaging landscape.</p><h4>The Database Inside Out</h4><p>Cosmos Db, Kafka and Event Hubs expose a distributed commit log sometimes known as a message log. They all have many more features and capabilities but a common attribute they all share is the ability to allow parallel consumers to serially read changes made by a publisher (writes). Each consumer must maintain a pointer to the place in the message log where they last read data. In simplistic terms when a consumer continually reads data from the log, processing the data and updating their pointer, they’re effectively processing a stream of data. <a href="https://medium.com/@gary.strange/cosmosdb-change-feed-processing-c002448a6ca">CosmosDB’s change feed</a> is not really intended for use as a Data Lake ingestion end-point and doesn’t have the additional features Kafka and Event Hubs provide. So we can discount CosmosDB change feed and focus on Kafka vs Event Hubs. The big advantage of Event Hubs is that it’s a Microsoft PaaS service and the big advantage of Kafka is the number of additional features it provides including schema registry and K-SQL streams. The Kafka vs Event Hubs is a lengthy debate and I don’t intend to cover all the pros and cons here. But for me, PaaS has such a significant advantage that Event Hubs has to be the tool of choice. Where it lacks features Microsoft will fill those gaps over time and in the interim period there are some very <a href="https://azure.microsoft.com/en-gb/blog/schema-validation-with-event-hubs/">clever workarounds</a>.</p><p>Crucially, Event Hubs provide bi-channel output, enabling the batch and speed layers. Let me explain, with <a href="https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-capture-overview">Event Hub Data Capture</a> messages read from the commit log are automatically package up into batch files ready for consumption by big data processing engines like <a href="https://azure.microsoft.com/en-gb/services/databricks/">Azure Databricks</a> or <a href="https://azure.microsoft.com/en-gb/services/sql-data-warehouse/">SQL Data Warehouse</a>. Thus enabling Deep learning, AI and Management Reporting capabilities. Configuring Event Hubs to use Event Data Capture means you can produce partitions of data from the stream of events being written to the hub. If you were to configure Event Capture to write a new batch every fifteen minutes you would essentially produce a new AVRO data file every quarter of an hour. Making the micro-services data available at the edge of its domain ready for collection by a batch consumer. For instance, an Azure Data Factory could be developed to periodically read the AVRO files from the Orders domain and write them to the Data Lake. Or better still configure <a href="https://azure.microsoft.com/en-gb/services/event-grid/">Event Grid</a> to trigger a notification every-time a new AVRO file is created via the Blob Storage integration. Using this pattern of collecting AVRO data from the operational domains satisfies traditional batch processing consumers like machine learning models, the batch processing layer in lambda architecture.</p><p>The messages can also be read from the Event Hub as a stream, exposing stream processing and <a href="https://azure.microsoft.com/en-gb/services/stream-analytics/">stream analytics</a> capabilities. The key benefit here is the timely-ness of data. If the organisation wants to know what’s happening when it’s happening then stream analytics is the answer.</p><h3>Evolving Batch Layer Architect</h3><p>The original micro-service architecture has now evolved to not only continue working as it did before but to also deliver data to batch consumers like the Data Lake.</p><p>Image 2: Extended order processing architecture, including data lake ingestion resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*aN3TA3Gkk0inJr7zv2wa5g.png" /></figure><ul><li><em>In the diagram, I depict Event Hubs as individual resources. This doesn’t necessarily mean they reside in individual Event Hub Namespaces. Deciding the topology of Event Hubs and Event Hub Namespaces is very organisation dependent.</em></li></ul><p>This new evolving architecture comes with many benefits.</p><h4>Replay From t0</h4><p>Being able to replay data from the **beginning of time is a significant advantage. New consumers may come on-line at arbitrary points in the future as the enterprise changes architecture, introduces new systems, migrates legacy systems or responds to data integrity objectives (DR, Audits). Scanning data in the OLTP system should be avoided to isolate the impact on business-as-usual. So having a cold store of your historical data allows downstream consumers to make repeated requests for any amount of source data. The source-team that implements this pattern can confidently say, in response to a data request “Sure, how much data would you like?” instead of “We’ll have some engineers figure out how to discretely extract it from the on-line system without interrupting the service. But we’ve got a lot on right now so you might have to wait a while”</p><p>**Well at least from when the Event Hub capture was first configured.</p><h4>Cold Storage for Longevity — Audit. Purge Hot Store</h4><p>Cold storage is cheap, very cheap. We can store huge amounts of data in cold storage like Azure Blob Storage or if you’re more familiar with AWS, S3 containers, for comparatively little expense. Hot stores like Cosmos DB and SQLDB are great for serving a high performance, scalable, highly available online experience, but storing huge amounts of data in these services becomes expensive. Having a reliable off-line cold store means that these exceptional online data systems can be purged of data that is no longer required on the hot path. Keeping them trim, responsive and cost-effective.</p><h4>Distributed Batch Packaging — Responsibility.</h4><p>Shipping containers; how would the world move large quantities of stuff without them? They’re uniform, so easily handled. The producer packs a whole bunch of stuff into them, they are shipped and then the consumer opens them up and unloads the goods inside. Simple and effective. Now imagine a world without shipping containers or even large storage boxes, what would our ports and docks look like? I imagine they’d have complex, intricate machinery and processes. So if a Data lake is a place where a lot of data gets shipped to, shouldn’t we adopt simple and effective methods of getting data there. Event Hub Capture distributes the responsibility of pre-packing data into containers before it leaves the producer. The responsibility of getting data shipped is now partially distributed and scalable. It’s just the process of unpacking the data and processing it that remains with the Data lake domain.</p><h4>Simply Ingestion Pattern-Just Copy</h4><p>With data pre-package, the process of shipping data becomes incredibly simple, just copy. The data can be pulled into the Data lake domain by either scheduling an ADF to periodically find new source files and copy them over or perhaps we could use Event Grid to fire a notification every time Event Hub Capture creates a new file. The new file event then triggers an ADF pipeline to go fetch the new file. Event Grid is a fairly new option in the messaging space and deserves its own analytical breakdown. But that’s for another day.</p><h4>Enables a Speed Layer</h4><p>As previously mentioned implementing Event Hubs lays the foundation for a speed layer to evolve when the business identifies use cases that require near-real-time data.</p><h4>Reconciliation</h4><p>Reconciliation is Data’s, <a href="https://en.wikipedia.org/wiki/Strange_Case_of_Dr_Jekyll_and_Mr_Hyde">Mr Hyde</a>. If you want to understand and evolve a business you analyse the organisation’s data. Data may need to travel through many of the organisation’s systems before it can be analysed, so data discrepancies are often introduced. Detecting data discrepancies can be difficult and finding the root cause even more taxing. Reconciling counts and aggregations across systems instils data trust and exposes potential data integrity issues. Putting the responsibility of packaging data within the produces domain means they can account for all data they have made available for consumers. The produces can count and aggregate the data they produced to provide reconciliation numbers for any consumer that wants to build data confidence or diagnose a data integrity issue.</p><h3>Closing Thoughts</h3><p>Data ingestion shouldn’t be complicated by piggybacking some data processing into the ingestion method. Practising ELT and moving away from more traditional ETL pipelines means we can get the data shipped from source quicker. Yes, there will be extra cleansing and sanitization to do but early data trust can be established by reconciling data received with data sent. A simple distributed ingestion pattern enables the organisation to bring new source-data-feeds under management at a much greater velocity. In the data-hungry world we operate in, no-one likes being told they have to wait for data. In my next story, I’ll be digging into the technical details of implementing this ingestion method and give some examples of using AVRO with pyspark.</p><h4>Influences</h4><p><a href="http://www.benstopford.com/aboutme/">Ben Stopford</a></p><p><a href="https://martin.kleppmann.com/">Martin Kleppmann</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65bc8b659570" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evolving into a Big Data-Driven Business in the Azure Cloud: Part I]]></title>
            <link>https://medium.com/@gary.strange/evolving-into-a-big-data-driven-business-in-the-azure-cloud-part-i-b89a2c971e32?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/b89a2c971e32</guid>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[azure-data-lake]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-lake]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Fri, 13 Sep 2019 08:05:11 GMT</pubDate>
            <atom:updated>2019-10-24T13:44:56.284Z</atom:updated>
            <content:encoded><![CDATA[<p>You might be surprised to learn that this article isn’t about machine learning and artificial intelligence. It&#39;s about the primitive that goes before those capabilities. The effort and understanding required to build a Data Lake in the Azure Cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*1KyQy1o3m25hCPef92jaEQ.png" /></figure><h4>The Early Days: The Monolith</h4><p>In later stories, I will cover <a href="https://azure.microsoft.com/en-gb/services/machine-learning-service/">Azure Machine Learning</a> but for now, we must start at the very beginning of time, well at least at the beginning of enterprise solutions.</p><p>I won’t bore you with yet another description of monolith architecture and the difficulties it presents. But I did want to highlight what I perceived to be a major advantage. In my experience when an organisation has grown a huge monolith operational system it’s often accompanied by an equally enormous data analytics function. Both systems have strongly typed schemas, storing tabular data, advantage number one. The second advantage is that the teams responsible for developing the operational entities have a responsibility and commitment to making the data available in the data analytics function. Once the data analytics function has grown to a vast size the team&#39;s responsibilities diverge but the early foundations were built by the same people that had to understand the operational systems and the business data within them. That understanding is then transferred to the analytical schemas. I see both these traits as advantages, advantages that can be lost when developing a Data Lake in the new world of mirco-service architecture and polyglot data storage.</p><h4>People Structure</h4><p>When organisations want to build a brand new application, that will make their current system look like a dinosaur, they’ll rightly embark on that adventure with a startup mentality. Acquire a little office on the other side of the road, fill it with their brightest minds and hire in a consultancy to accelerate new tech adoption and deliver the MVP. Whilst this might make a lot of sense when delivering features based applications, utilising a stockpile of feedback gathered from customers over an extensive period of time. It doesn’t seem to make a lot of sense when developing a Data Lake. There is no stockpile of customer feedback explicitly directing the feature requirements, no <a href="https://en.wikipedia.org/wiki/Net_Promoter">net-promoter-scoring</a> to help guide the priorities. No detailed explanation as to exactly what we hope to achieve! Just an understanding that if we put all the data in one accessible platform good things will happen because that&#39;s what the tech giants have done.</p><p>Building the next generation of an application can be done within the confines of a single domain. Therefore all the business understanding and context can be captured and managed with non-trivial but feasible effort. A Data Lake will ingest data from all corners of the organisation so the domain knowledge is as far spread as the disparate data sources. Expecting one central team to manage all the relationships and capture all the data understanding required is not a feasible approach. It’s a funnel-shaped problem with lots of teams working on systems that are producing data and one team struggling to broker relationships and master the understanding of the business context the data represents.</p><p>The source teams also have no incentive to supply accurate trustworthy accounts of the data their system produces. So the centralised team quickly become their own delivery bottleneck as they don’t have the bandwidth to bring the extensive list of data sources under management. Instead, the source teams need to be responsible for ensuring that their data is ingested into the lake and they are also responsible for any metadata required to interpret the data they’ve published, treating the data as ‘product’ they export to customers. In return, the source teams can be early beneficiaries of the Data Lake by giving them secure access to data in the lake that originated from their systems. Thus creating a reciprocal relationship. You might think why should the source teams care about having access to their data in the lake. It’s their data, they already have access to it within their domain. Having a replicated copy of their operational data available for analytics is extremely valuable as it gives the teams the opportunity to derive value and insight from patterns they are yet to discover, without impacting the production workload.</p><p>For example, the team might release a feature that they expect will drive new user registrations. Being able to analyse and understand the characteristics of the data before and after the feature release will give the team the ability to measure success. Moreover, having engineering teams working closely with the data in the lake makes them the experts of the data in its new form and location. Any queries coming from other parts of the enterprise concerning their data in the lake can be serviced by the individuals that know that data best.</p><p>Many organisations have or are in the process of moving away from the monolith. With this revolution, there’s been a paradigm shift in operational systems. Architects and engineers are moving away from traditional transactions over stateful data in relational data stores to eventually consistent architectures storing event-based data in non-relational distributed systems like CosmosDB. This new way of storing data comes with many benefits but it also has some drawbacks. I consider relational SQL engines to be the Swiss Army Knife of data technologies. They can host highly concurrent OLTP workloads very effectively but can also expose the data they store to ad-hoc queries and analytics. With a relational engine, you can service business transactions and at the same time produce queries and views to understand patterns stored in the data. Imagine you&#39;re in the middle of a technical crisis and the CIO needs to know right now how many accounts are impacted by a bug in the system. In a relational system, this would be a fairly trivial low impact query. In a no-SQL distributed storage engine like CosmosDB ad-hoc cross-document queries have the potential to spike the <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/request-units">request unit</a> consumption beyond the provisioned wallet, thus throttling actual user requests. So, in my opinion, it’s too dangerous to run any “I need this number, now” queries on the operational system. “Tell us something we don’t already know?” Enterprises have been separating their OLTP and OLAP workloads for centuries. Why can’t the teams just get what they need from the data warehouse? Well in a modern cloud-based architecture where the majority of operational systems are now using document databases to process transactions it will take some time to build the warehouse. I’ve done the maths on this and I calculate it will take <a href="https://simple.wikipedia.org/wiki/42_(answer)">42</a> light-years to add every single attribute in the enterprise to the dimension and fact tables of the warehouse. Why so long? impedance mismatch debt. In the era when relational engines reigned supreme application programmers were forced to collapse their class structures of nested objects into normalised tabular forms, to efficiently store and retrieve data from the relational engine (strict schema on write). So effectively you had many souls working away to solve the impedance mismatch problem. In this new era, NoSQL technologies sell themselves on the promise that the impedance mismatch problem is no longer a problem that needs solving. Now trust me on this, this is a big selling point to software engineers. I’ve spent many a year working as a data engineer and had many conversations with software engineers over technology choice and found their disdain for maintaining mapping layers like NHibernate, Dapper or EF incredible. It’s as if relational supremacy was my fault and I personally had imprisoned them in ORM hell for all these years. Thus, the opportunity to adopt NoSQL technologies, abandoning the need to manage mappings somehow makes up for the wrongs they experienced whilst incarcerated. If you read any of <a href="https://medium.com/@gary.strange/cosmosdb-change-feed-processing-c002448a6ca">my articles</a> or watch any of <a href="https://www.youtube.com/watch?v=3UrA7aWdlfs&amp;list=PLyCdJcoei3eBBRoSfXsdtIigsITyCDSwz&amp;index=2&amp;t=49s">my videos</a> you’ll see I’m actually a big fan of NoSQL technologies, in particular, CosmosDB. It’s awesome for the right use case! Coming back to my point, adopting NoSQL technologies and dropping ORM doesn’t mean the work the ORM was doing evaporated. It’s just becoming someone else&#39;s problem. Why? well, the operational systems world may have moved on but many organisations have well-established OLAP architecture who’s primary source of data is a relational store. Just as relational databases have reigned supreme <a href="https://www.kimballgroup.com/data-warehouse-business-intelligence-resources/kimball-techniques/dimensional-modeling-techniques/star-schema-olap-cube/">Kimball’s star schema</a> has also had overwhelming success. Yes, analytical technologies have evolved to source from a panoply of disparate sources but fundamentally a great deal of data is still stored and sourced from relational tabular schemas. So the impedance mismatch problem has now moved downstream to anyone who needs data in a schema-on-write tabular store. The Data Lake shouldn’t care about the needs and wants of every data consumer. If it attempts to curate specialised forms of data for all, it will be pulled in all directions becoming a centralised fat-berg blocker. As consuming teams exert their problems upon the data engineers that now have the job of keeping everyone happy. That&#39;s where this beautiful term schema-on-read comes into play and really resonates with me. In short, the data is stored as-is, how we received it, how it was originally published. If you want or need the data in a different shape well guess who’s job that is buddy? This remains true until there is a collective realisation that some refined views need promoting to materialised views as many consumers share the same requirements and the compute required to process the data becomes unpalatable. Raising the question of who is responsible for maintaining these views. This responsibility should reside where possible with the teams that know the data best, distributing the responsibility instead of centralising it. However, the design and creation of views should not supersede the ingestion of raw data. Data first, refinement comes later.</p><h4>Data Swamp Fear Motivates Data Prison</h4><p>Balancing data security and governance with accessibility and delivery velocity is extremely difficult. I’m surprised someone hasn’t described a GAV theorem where elements Data Governance, Accessibility and Delivery Velocity are traded off against each other. A Data Lake with poor data governance will bring feeds under management at a greater pace but won’t necessarily make the data very accessible as it will be scattered in an un-organised fashion across multiple storage assets (data swamp). A data lake with good data governance will set the foundations for organised, secure, data structures making data easily accessible at the cost of being much slower to develop. At one extreme, we can create a data swamp at pace and at the other extreme we slowly construct a maximum-security data prison. At both of these extremes, data accessibility is the victim.</p><h4>Making Data Flow: Lambda vs Kappa</h4><p>Lambda and Kappa architectures are big subjects and I don’t intend to cover them here. But whether you agree or disagree with either of the architectural approaches isn’t important. Building a big data platform that exposes data for stream analytics is important.</p><p>Where previously we had service-orientated-architecture (SOA) we now have micro-services. When considering data-driven intelligence, micro-service architecture exposes messages as unbounded streams of data, as they communicate events to other services within the enterprise. For example, an Orders service communicates order processing events to the Payments services when card payments need to be processed. Which is great as we have an existing event endpoint we can subscribe to and route these out-going messages to new analytical capabilities. Having access to near-real-time events opens the door to near-realtime intelligence. I like to think of the data as being in-flight, like oxygen and hydrogen atoms buzzing around in the atmosphere. They can be emitted from the leaves of a publishing micro-service and breathed in by a subscribing micro-service. Admittedly atoms travel around in a somewhat chaotic manner unlike a good micro-service architecture but the pure rawness of atoms really hits a bell with me. In the same way that oxygen and hydrogen can become organised to make water in a lake. Message data can be organised to make partitions of parquet files in a Data Lake. Unfortunately, this organisation process stabilises the data ready for batch analysis and the opportunity to perform near-real-time intelligence is lost. As water can once again lose its organisation and become free atoms. Stationary data on the lake can be shredded back into a stream of events. However, time can not be re-materialised and the opportunity to make near-real-time decisions is gone. Don’t make data stored in the lake a precursor to making intelligent decisions. Don’t make streaming analytics a secondary concern. Tap into the streams of data as they’re making their journey to the lake.</p><h4><strong>Education and Discoverability</strong></h4><p>It’s important to not overlook the importance of upskilling employees with the skills they need to use data effectively and to also make accessing and understanding data intuitive. Data that&#39;s difficult to find becomes effectively lost and the effort put into capturing and preserving it becomes wasted effort. Organisations might use a mixture of share-point, confluence, github and other platforms for publishing internal documentation. With many teams using many different publishing technologies, it can become difficult to create a consistent central catalogue of the data that&#39;s available for ingestion and indeed analysis. Let us consider some examples from our day-to-day lives which may reflect the problem of making data discoverable.</p><p>Starting with my kid&#39;s toy boxes. They’re packed full toys of all shapes and sizes, some were a massive hit with the kids others not so much. However, as they are all stuffed into various boxes and containers, only the ones at the top are discoverable. Consequently, regardless of the toy’s merit, only a few get played with regularly, the others can be considered lost. How about a Library? now we’re getting there, ordered and categorized publications by many authors. But a bit of a fuddle to find the exact information you’re looking for. Google…em, I meant Bing? Masses of discoverable information with a simple interface, yes please. In essence, we need two things to make datasets discoverable, a community of publishers and a search engine.</p><p>With data discovery services in place, employees can then start solving problems with data and upskill themselves by tapping into the datasets and metadata collated in a centralised knowledge repository. <a href="https://docs.microsoft.com/en-gb/azure/data-catalog/">Azure Data Catalog</a> provides publishing capabilities, data tagging, data sampling and a search engine. In future articles, I’ll expand on the usage of a Data Catalog and how one might be built alongside your data.</p><h4>End of Scene One</h4><p>I covered a lot of the topics which I hope demonstrates why it’s difficult to build a Data Lake and become a big-data-driven organisation. In the next part of this story, I’ll get into more technical details and discuss how a Data Lake can be forged in Microsoft Azure.</p><h4>Influences</h4><ul><li><a href="https://martin.kleppmann.com/">Martin Kleppmann&#39;s blog</a></li><li><a href="https://martinfowler.com/articles/data-monolith-to-mesh.html">How to Move Beyond a Monolithic Data Lake to a Distributed Data Mesh</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b89a2c971e32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flattening JSON in Azure Data Factory]]></title>
            <link>https://medium.com/@gary.strange/flattening-json-in-azure-data-factory-2f2130794258?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f2130794258</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[azure-data-factory]]></category>
            <category><![CDATA[parquet]]></category>
            <category><![CDATA[azure-data-lake]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Tue, 07 May 2019 17:37:33 GMT</pubDate>
            <atom:updated>2019-05-08T20:15:26.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*d0b3uljjk3yAshWM2iiljg.png" /></figure><p>JSON is a common data format for message exchange. Its popularity has seen it become the primary format for modern micro-service APIs. JSON allows data to be expressed as a graph/hierarchy of related information, including nested entities and object arrays. It benefits from its simple structure which allows for relatively simple direct serialization/deserialization to class-orientated languages.</p><p>Many enterprises maintain a BI/MI facility with some sort of Data warehouse at the beating heart of the analytics platform. Typically Data warehouse technologies apply schema on write and store data in tabular tables/dimensions. When ingesting data into the enterprise analytics platform, data engineers need to be able to source data from domain end-points emitting JSON messages. Messages that are formatted in a way that makes a lot of sense for message exchange (JSON) but gives ETL/ELT developers a problem to solve. How to transform a graph of data into a tabular representation.</p><p>There are many methods for performing JSON flattening but in this article, we will take a look at how one might use ADF to accomplish this. Microsoft currently supports two versions of ADF, v1 and v2. The content here refers explicitly to ADF v2 so please consider all references to ADF as references to ADF v2.</p><p>I’ll be using Azure Data Lake Storage Gen 1 to store JSON source files and parquet as my output format. Although the storage technology could easily be Azure Data Lake Storage Gen 2 or blob or any other technology that ADF can connect to using its JSON parser. Again the output format doesn’t have to be parquet. But I’m using parquet as it’s a popular big data format consumable by spark and SQL polybase amongst others.</p><p>My test files for this exercise mock the output from an e-commerce returns micro-service.</p><p>Here is an example of the JSON:</p><pre>{<br>    &quot;returnReference&quot;: &quot;4829U3N35MKR9E&quot;,<br>    &quot;orderReference&quot;: &quot;02KY5KL1Q21S&quot;,<br>    &quot;customerId&quot;: 201582644,<br>    &quot;items&quot;: [<br>        {<br>            &quot;variantId&quot;: 613941,<br>            &quot;quantity&quot;: 1,<br>            &quot;returnReason&quot;: {<br>                &quot;code&quot;: 1,<br>                &quot;notes&quot;: &quot;Too Large&quot;<br>            }<br>        },<br>  {<br>            &quot;variantId&quot;: 713941,<br>            &quot;quantity&quot;: 5,<br>            &quot;returnReason&quot;: {<br>                &quot;code&quot;: 2,<br>                &quot;notes&quot;: &quot;Doesn&#39;t suit me&quot;<br>            }<br>        }<br>    ],<br>    &quot;timestamp&quot;: &quot;2017-12-28T13:51:46.2671616Z&quot;<br>}</pre><p>In the JSON structure, we can see a customer has returned two items. Those items are defined as an array within the JSON. This file along with a few other samples are stored in my development data-lake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2OfX6LkTgkLrwD_IOGfuvg.png" /><figcaption>Azure Data Lake Gen 1</figcaption></figure><p>So we have some sample data, let&#39;s get on with flattening it. My ADF pipeline needs access to the files on the Lake, this is done by first granting my ADF permission to read from the lake. I used <a href="https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview">Manage Identities</a> to allow ADF to have access to files on the lake.</p><p>For those readers that aren’t familiar with setting up Azure Data Lake Storage Gen 1 I’ve included some guidance at the end of this article. I’m going to skip right ahead to creating the ADF pipeline and assume that most readers are either already familiar with Azure Datalake Storage setup or are not interested as they’re typically sourcing JSON from another storage technology.</p><h3>ADF Pipeline</h3><p>First off, I’ll need an Azure DataLake Store Gen1 linked service. I set mine up using the Wizard in the ADF workspace which is fairly straight forward. Don’t forget to test the connection and make sure ADF and the source can talk to each other. If you hit some snags the Appendix at the end of the article may give you some pointers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*mQFNq-8ejOhzkYzQD95a1Q.png" /></figure><h4>JSON Source Dataset</h4><p>Now for the bit of the pipeline that will define how the JSON is flattened. Add an Azure Data Lake Storage Gen1 Dataset to the pipeline. Alter the name and select the Azure Data Lake linked-service in the connection tab.</p><p>Next, select the file path where the files you want to process live on the Lake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQ8wJ_zWmLsSNsZflJkO8Q.png" /></figure><p>To configure the JSON source select ‘JSON format’ from the file format drop down and ‘Set of objects’ from the file pattern drop down.</p><p>Hit the ‘Parse JSON Path’ button this will take a peek at the JSON files and infer it’s structure. It’s worth noting that as far as I know only the first JSON file is considered. So you need to ensure that all the attributes you want to process are present in the first file.</p><p>To explode the item array in the source structure type ‘items’ into the ‘Cross-apply nested JSON array’ field. This will add the attributes nested inside the items array as additional column to JSON Path Expression pairs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLa4tzU4shbD4awVsTju2A.png" /></figure><p>All that&#39;s left to do now is bin the original ‘items’ mapping. If left in, ADF will output the original ‘items’ structure as a string. Including escape characters for nested double quotes. Although the escaping characters are not visible when you inspect the data with the ‘Preview data’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJjOpqa2zFeFtHeVQEEEAQ.png" /></figure><p>This is the bulk of the work done. All that&#39;s left is to hook the dataset up to a ‘copy activity’ and sync the data out to a destination dataset.</p><p>I sent my output to a parquet file. The flattened output parquet looks like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*8YsS23Qa2DqNKqd4E1Y57Q.jpeg" /></figure><p>I’m using an open source <a href="https://github.com/mukunku/ParquetViewer">parquet viewer</a> I found to observe the output file. The input JSON document had two elements in the items array which have now been flattened out into two records.</p><p>I was able to create flattened parquet from JSON with very little engineer effort. That makes me a happy data engineer.</p><h4>Not So Good</h4><p>I got super excited when I discovered that ADF could use JSON Path expressions to work with JSON data. Sure enough in just a few minutes, I had a working pipeline that was able to flatten simple JSON structures. However, as soon as I tried experimenting with more complex JSON structures I soon sobered up. It’s certainly not possible to extract data from multiple arrays using cross-apply. Part of me can understand that running two or more cross-applies on a dataset might not be a grand idea. But I’d still like the option to do something a bit nutty with my data. I tried a possible workaround. What would happen if I used cross-apply on the first array, wrote all the data back out to JSON and then read it back in again to make a second cross-apply? This isn’t possible as the ADF copy activity doesn’t actually support nested JSON as an output type. JSON structures are converted to string literals with escaping slashes on all the double quotes. So when I try to read the JSON back in, the nested elements are processed as string literals and JSON path expressions will fail.</p><p>Here is an example of the input JSON I used. You’ll see that I’ve added a carrierCodes array to the elements in the items array.</p><pre>{<br>  “returnReference”: “4829U3N35MKR9E”,<br>  “orderReference”: “02KY5KL1Q21S”,<br>  “customerId”: 201582644,<br>  “items”: [<br>    {<br>      “variantId”: 613941,<br>      “quantity”: 1,<br>      “returnReason”: {<br>        “code”: 1,<br>        “notes”: “Too Large”<br>      },<br>      “carrierCodes”: [ “20000K”, “20005K”, “40000K” ]<br>    },{<br>      “variantId”: 713941,<br>      “quantity”: 5,<br>      “returnReason”: {<br>        “code”: 2,<br>        “notes”: “Doesn’t suit me”<br>      },<br>      “carrierCodes”: [ “20000K”, “20005K”, “40000K” ]<br>    }<br>  ],<br>  “timestamp”: “2017–12–28T13:51:46.2671616Z”<br>}</pre><p>As mentioned if I make a cross-apply on the items array and write a new JSON file, the ‘carrierCodes’ array is handled as a string with escaped quotes.</p><pre>{<br>  “returnReference”: “4829U3N35MKR9E”,<br>  “orderReference”: “02KY5KL1Q21S”,<br>  “customerId”: 201582644,<br>  “timestamp”: “2017–12–28T13:51:46.2671616Z”,<br>  “variantId”: 613941,<br>  “quantity”: 1,<br>  “code”: 1,<br>  “notes”: “Too Large”,<br>  “carrierCodes”: “[\”20000K\”,\”20005K\”,\”40000K\”]”<br>},{<br>  “returnReference”: “4829U3N35MKR9E”,<br>  “orderReference”: “02KY5KL1Q21S”,<br>  “customerId”: 201582644,<br>  “timestamp”: “2017–12–28T13:51:46.2671616Z”,<br>  “variantId”: 713941,<br>  “quantity”: 5,<br>  “code”: 2,<br>  “notes”: “Doesn’t suit me”,<br>  “carrierCodes”: “[\”20000K\”,\”20005K\”,\”40000K\”]”<br>}<br></pre><p>I hope you enjoyed reading and discovered something new about Azure Data Factory.</p><h4>Appendix: Azure Datalake Storage Setup</h4><p>I’ve added some brief guidance on Azure Datalake Storage setup including links through to the official Microsoft documentation.</p><p>In the article, <a href="https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/overview">Manage Identities</a> were used to allow ADF access to files on the data lake. There are a few ways to discover your ADF’s Managed Identity Application Id.</p><ol><li>You can find the Managed Identity Application ID via the portal by navigating to the ADF’s General-Properties blade.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BcUHImpbAykkLJ2Cqr6mQ.png" /></figure><p>2. You can also find the Managed Identity Application ID when creating a new Azure DataLake Linked service in ADF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*nggds07hQ-i_9SrEukqGfQ.png" /></figure><p>Once the Managed Identity Application ID has been discovered you need to configure Data Lake to allow requests from the Managed Identity. For the purpose of this article, I’ll just allow my ADF access to the root folder on the Lake.</p><p>Via the Azure Portal, I use the DataLake Data explorer to navigate to the root folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHdpyVdUuLmEGylHIt2OWg.png" /></figure><p>From there navigate to the Access blade. Then its ‘add’ button and here is where you’ll want to type (paste) your Managed Identity Application ID. For a comprehensive guide on setting up Azure Datalake Security visit: <a href="https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-secure-data">https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-secure-data</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*eGqkVrm3FhyGNn9_kNrBbg.png" /></figure><p>Azure will find the user-friendly name for your Managed Identity Application ID, hit select and move onto permission config. For this example, I’m going to apply read, write and execute to all folders. I’ve also selected ‘Add as: An access permission entry and a default permission entry’. For a more comprehensive guide on ACL configurations visit: <a href="https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-access-control">https://docs.microsoft.com/en-us/azure/data-lake-store/data-lake-store-access-control</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*njJ-XvC8spZlUmsrDw7QkQ.png" /></figure><h4>Credits</h4><p>Thanks to <a href="https://www.linkedin.com/in/jasonhorner/">Jason Horner</a> and his session at <a href="https://sqlbits.com/">SQLBits 2019</a></p><p>Imagery from:<br><a href="https://www.freepik.com/">Freepik</a><br><a href="https://www.flaticon.com/authors/smashicons">Smashicons</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f2130794258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding CosmosDB Continuation Tokens (HasMoreResults) and ConnectionPolicy RequestTimeouts]]></title>
            <link>https://medium.com/@gary.strange/understanding-cosmosdb-continuation-tokens-hasmoreresults-and-connectionpolicy-requesttimeouts-3ed1fadfa81d?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ed1fadfa81d</guid>
            <category><![CDATA[continuation-tokens]]></category>
            <category><![CDATA[cosmosdb]]></category>
            <category><![CDATA[connection-policy]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[request-time-out]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 16:38:32 GMT</pubDate>
            <atom:updated>2018-11-27T20:23:04.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Continuation Tokens</h3><p>The CosmosDB client libraries utilize a continuation strategy when managing the results returning from queries. Every query submitted to CosmosDB will have a MaxItemCount limit attribute in the request header. The default limit is 100; however, any Int32 value can be used. This value is not the definitive ceiling, and other constraints can come into effect and reduce the ItemCount in a more dynamic manner. We will come back to this point later. Requests exceeding the MaxItemCount response constraint are paginated. The first page is returned to the client with a partial result and response headers. Within the response headers, a continuation token (“x-ms-continuation”)is present indicating that only a partial result was returned and that more records are available on request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlizA0BnTO7CmQf1t0QFww.png" /><figcaption>Example continuation token and record count.</figcaption></figure><p>Further pages of records can then be retrieved by supplying the continuation token in subsequent calls. The coordination between the CosmosDB service and the client is taken care of behind the scenes by the SDKs. All the developer needs to do is check the HasMoreResults boolean on the DocumentClient object. If HasMoreResults is true, there is an opportunity to get more records. Calling the ExecuteNext method will retrieve the next page of results.</p><p>For example, a very simple code example might look something like this…</p><pre>public async static void RequestDocuments&lt;T&gt;(<br>    DocumentClient client,<br>    string collectionLink,<br>    string query)<br>{<br>    using (var queryable = client.CreateDocumentQuery&lt;T&gt;(<br>        collectionLink, query,<br>        new FeedOptions() ).AsDocumentQuery())<br>    {<br>        while (queryable.HasMoreResults)<br>        {<br>            foreach (T item in <br>                await queryable.ExecuteNextAsync&lt;T&gt;())<br>            {<br>                // Iterate through results.<br>            }<br>        }<br>    }<br>}</pre><h3>RequestTimeout</h3><p>The RequestTimeout property on the CosmosDB SDKs ConnectionPolicy class can be miss-leading. If you’re coming from an RDBMS background, it’s easily confused with the CommandTimeout property found in classes like SqlCommand. The expectation of any timeout parameter is to terminate an activity after a defined period has elapsed. Setting the CommandTimeout property on the SqlCommand class means that a T-SQL query sent to the server must complete in the set period or the activity is terminated and an exception is raised. ConnectionPolicy.RequestTimeout does implement the same time limit logic, but the CosmosDB client handles database interaction in a very different manner when compared to traditional RDBMS SDKs. With RDBMS the query author has virtually no limitations. It’s possible to query huge amounts of data and consume vast amounts of system resources without consideration for any other uses on the system.</p><p>CosmosDB is different; client libraries expose numerous query methods and these methods implement a continuation strategy. The idea of sending a query, with unlimited compute consumption, to the data store and returning unbounded sizes of datasets has been abolished. CosmosDB has been designed from the ground up with massive data volumes and predictable performance in mind. So there are some in-movable but configurable caps and limits in play when using the client libraries. A combination of various caps and limits mean that returning results have finite boundaries.</p><p>Now we have an understanding of the continuation mechanism we can fully understand how the RequestTimeout constraint works. The timeout is not applicable to the gross compute time of the query but applies to the partial compute time. The query is broken down into batches of resultsets using continuation tokens and its those individual partial result sets that are governed by the request timeout. To put it another way, for each call to ExecuteNextAsync() the timer is reset.</p><p>For example, if my MaxItemCount is 100, RequestTimeout is 1 second and my query returned 500 documents. The initial call would return 100 documents and a continuation token. I would then need to make four more ExecuteNextAsync() executions to return the complete result set. If each request executed in 500ms (I have a slow but consistent network) then my gross request time would be 2.5 seconds and I would not receive a RequestTimeout as each component part of the total request executed in less than 1 second.</p><h3>Long Running Queries</h3><p>With this new knowledge in mind, you can appreciate that it’s possible to have long-running queries. If the query returns a large amount of data, many requests will be executed in the continuation loop and the total time will add up.</p><h4>Query Request Timeout</h4><p>It is possible to implement some defensive coding to mitigate the risk of a rogue query running away and consuming excessive RUs. This constraining behaviour can be achieved by adding a simple timeout to the paging loop.</p><p>For example</p><pre>int TotalRequestTimeout_ms = 10000; // 10 seconds<br>int TotalRequestUnit_budget = 100; // 100 RU</pre><pre>Stopwatch sw = Stopwatch.StartNew();<br>double requestUnitsConsumed = 0;<br>int requestCount =0;</pre><pre>while (prices.HasMoreResults)<br>{<br>    response = await prices.ExecuteNextAsync&lt;PricePoint&gt;();<br>    requestUnitsConsumed += response.RequestCharge;<br>    requestCount += response.Count;<br>    foreach (PricePoint p in response)<br>    {<br>        pp.Add(p);<br>    }<br>    if (sw.ElapsedMilliseconds &gt; TotalRequestTimeout_ms) throw new Exception(&quot;TotalRequest time out!&quot;);</pre><pre>if (requestUnitsConsumed &gt; TotalRequestUnit_budget) throw new Exception(&quot;TotalRequestUnits budget breached!&quot;);<br>}</pre><p>The code used here is to simply illustrate the concept and is not a coding recommendation.</p><h3>Other Constraints</h3><p>Previously I mentioned that there are other constraints that can affect the number documents returned by a query. I’ll cover them briefly here.</p><h4>RU Limit</h4><p>If a request call is made via the SDK after the target CosmosDB collection has exceeded the RU capacity provisioned the request will be terminated and an exception is thrown with an <a href="https://docs.microsoft.com/en-gb/rest/api/cosmos-db/http-status-codes-for-cosmosdb">HTTP 429 status</a> code.</p><h4>*4MB Packet SIze Limit</h4><p>The response dataset payload is restricted to 4MB in size. If I set the MaxItemCount to something big like 10000 and my document size is k kilobytes then (k * number-of-documents) must be less than 4096 Kb (4 MB). As an example, imagine your average document size is 0.6kb then you could only fit 6990 documents into a 4MB chunk. Even if I set my MaxItemCount to 10000 it would still only receive 6990 documents per request.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ed1fadfa81d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CosmosDB Change Feed Processing]]></title>
            <link>https://medium.com/@gary.strange/cosmosdb-change-feed-processing-c002448a6ca?source=rss-3e25bbe2c359------2</link>
            <guid isPermaLink="false">https://medium.com/p/c002448a6ca</guid>
            <category><![CDATA[data-replication]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[change-feed]]></category>
            <category><![CDATA[cosmosdb]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Gary Strange]]></dc:creator>
            <pubDate>Tue, 12 Jun 2018 10:33:47 GMT</pubDate>
            <atom:updated>2018-06-12T10:34:18.666Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This article was created to help readers understand CosmosDB change feed processing. The knowledge gathered here has been achieved by prototyping change feed solutions, numerous discussions with the Microsoft Product team and more recently production implementations. This know-how is distilled here in a simplified form.</p><h3>What is the Change Feed?</h3><p>Microsoft describe the Change Feed as follows</p><blockquote><em>With change feed support, Azure Cosmos DB provides a sorted list of documents within an Azure Cosmos DB collection in the order in which they were modified. This feed can be used to listen for modifications to data within the collection and perform actions.</em></blockquote><p>One thing that’s not abundantly clear in the MS documentation is that the modification notifications are aggregated and the notification is actually the latest version of a document. No explicit CRUD actions are exposed. For example, the data retrieved from the change feed will not include metadata identifying an insert or update explicitly. If a document is modified many times in succession between change feed reads you will not be able to access the intermediate state changes. For example, consider the document modification journey insert→modification→modification. If the change feed is read after the three CRUD operations complete you will only see the document state of the aggregated changes. You will not have access to the state after insert or the state after the first modification. The final state, after the second modification, is all that is emitted from the change feed. Deleted documents are not currently captured by the change feed. There is currently a workaround, using soft deletes and TTL.</p><h3>What is the Change Feed Used For?</h3><p>There are many applications for the Change Feed and Microsoft highlight many in <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/change-feed">this</a> document. One of the simplest use cases is to simply migrate data to a target storage technology.</p><p>Let’s look at a typical topology for simple change feed processing. The topology includes exploiting the geo-redundancy capabilities of the CosmosDB product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFaFZlMa5GNS2-fLl9AeFg.png" /></figure><p>The change feed journey starts when an application inserts a document to the primary write region (the leader) of a CosmosDB collection. For the purpose of this documentation consider all transaction to be using the bounded staleness <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/consistency-levels">consistency level</a>. CosmosDB’s internal local LSN (logical sequence number) is atomically incremented as part of the document insert operation. The LSN is broadcast to the secondary region (the follower). The follower is now aware that it is behind the leader and must catch up. The follower catches up by pulling the missing LSN transaction from the leader.</p><p>This is a rather crude depiction of the geo-replication used by CosmosDB. But it’s important to understand that LSN’s are being used to coordinate transactions and data across regions and that LSN’s are used to coordinate the change feed reads.</p><h3>How Does Change Feed Processing Work?</h3><p>Out of the box, the change feed is accessible by the CosmosDB client SDK and the CosmosDB REST API.</p><p>CosmosDB partitions are layers of compute and storage. Each partition manages a physical portion of the collection data and each partition has its own LSN to keep track of transactions. Change feed leases can be compared to reading a novel. You pick the book up, read it in sequence (page by page) for a period of time and then you need to put the book down. You don’t want to lose the page that you read last so you use a bookmark to conveniently pick up where you left off. In CosmosDB there are many partitions so one bookmark per partition needs to be maintained. The change feed lease collection is used to store a lease document per partition, the document includes the LSN bookmark. This lease collection can be any durable storage, it doesn’t have to be CosmosDB. However, all the implementations I’ve worked on to date use CosmosDB to store the leases.</p><h3>Change Feed Processing Implementation Options</h3><p>There are a few options when it comes to developing a change feed processor. Whether you want to create a push or pull mechanism limits those choices. The sections below summaries the possible options in order of difficulty</p><h4>Write your own</h4><p>This is the most difficult but flexible option. With this option both push and pull data subscription is possible.</p><p>The client SDK has a number of methods available for reading the change feed. In it’s simplest form <a href="https://msdn.microsoft.com/library/azure/microsoft.azure.documents.client.documentclient.readpartitionkeyrangefeedasync.aspx">ReadPartitionKeyRangeFeedAsync </a>gets a partition key range per physical partition. The key range represents the upper and lower bounds of the partitioned data. If the partition key was alphabetical, the first partition may have range A-C and the second partition may have D-E and so forth. However partition keys are hashes of the logical key values, so the key ranges are incomprehensible to the human eye. <a href="https://msdn.microsoft.com/library/azure/microsoft.azure.documents.client.documentclient.createdocumentchangefeedquery.aspx">CreateDocumentChangeFeedQuery </a>can then be invoked for each partition range returned by the ReadPartitionKeyRangeFeedAsync call. To create partition bookmarks (leases) you’ll need to persist the response.continuation tokens in durable storage.</p><h4>Utilize the Change Feed Library</h4><p>This option is fairly straightforward to implement and offers a degree of flexibility. It’s only possible to implement push data subscription.</p><p>The change feed library is available as a NuGet package. So all you’ll have to do is reference it in your project and make sure you provide the relevant environment config; CosmosDB account URL, auth key and lease DB collection details (the change feed library expects the leases to be stored in cosmosdb). Once the NuGet is referenced, it a simple case of writing a custom IChangeFeedObserver to process the document changes.</p><h4>Change Feed Azure Functions</h4><p>Microsoft announced the release of Azure Function for change feed at Ignite 2017. Using the new CosmosDB Azure Function template you’re able to construct server-less code that processes an array of documents. Microsoft effectively hosts the change feed library as a service on their internal infrastructure. The feed is constantly read for changes and the changes are then passed synchronously to the Azure Function as an input array. (the Azure Function template expects the leases to be stored in CosmosDB)</p><h3>Illustration</h3><p>Once change feed processing code is implemented it’s just a case of creating some actions in response to the change data. In this simple illustration, the data is idempotently stored away in durable storage. Changes are read from the change feed in LSN order per partition. Chronological ordering across partition is not guaranteed. This is not an issue if the documents are atomic, with no dependency on related documents.</p><h4>Geo-Replication with Change Feed</h4><p>Having a secondary geo-replicated region is not necessary for change feed processing to occur. It is perfectly plausible to read the change feed from a non-geo-replicated region (single region topology). However, the vast majority of high SLA environments will adopt an HA/DR strategy including one or more geo-replicated regions. CosmosDB is a single master global distributed system, geo-replicated provisioning constraints mean that each region in the failover group has an equal amount of RU provisioned. Change Feed reads have an RU charge, so funnelling all the change feed request to a secondary region means that the additional read load is isolated from the primary read. This isolation allows the OLTP throughput of the application to be monitored separately.</p><h4>Change Feed Step-By-Step</h4><blockquote><strong>Step 1</strong></blockquote><p>The client application writes a document to the primary write region (leader). LSN 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*cGSyjIeu-0Xd5Bna-1JyiA.png" /></figure><blockquote><strong>Step 2</strong></blockquote><p>The document is replicated to the secondary geo-graphical region (follower). LSN1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*S3sbrodb_CHw_NPCHk0V6g.png" /></figure><blockquote><strong>Step 3</strong></blockquote><p>The change feed processor reads the change feed and the document is returned along with the LSN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*y0THVtbaQAy9lpckCeF-DQ.png" /></figure><blockquote><strong>Step 4</strong></blockquote><p>The document is persisted to durable storage using an idempotent operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*seyEtmZOT2H_lF9UJcYJPw.png" /></figure><blockquote><strong>Step 5</strong></blockquote><p>After completion of the write to storage the lease document is updated with the new LSN 1 (bookmark).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*K5OW_nyxi4QZta2U4EYm5A.png" /></figure><p>When a second document is written by the client application or the original document is updated by the client application, the LSN moves onto value 2 (step 1). Geo-replication takes place (step 2) and the secondary region is updated to LSN 2. The change processor retrieves the lease document from the lease store. This lease document has the LSN 1, which is then passed as part of the request header to the change feed. This tells the change feed to only return changes after LSN 1 (step 3). The document is then idempotently committed to the durable storage and the lease is updated with LSN 2 (step 4 and 5)</p><h3>Change Feed Hosting Recommendations</h3><p>Defining the number of change feed processing instances to host depends on the amount of RU throughput provisioned. Microsoft recommends that you provision one change feed processing instance per 1000RU provisioned for the collections. For example, a collection with 2500RU should have 3 change feed processing instances.</p><p>To achieve greater compute density Microsoft also recommend provisioning multiple instances of the change feed processor on a single VM host or Service Fabric cluster node. Having an affinity between the number of collection partitions and change feed processing instances is not desired as it under utilities overall system resources. Moreover having more change feed instances than collection partitions is a great way to waste compute.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c002448a6ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>