<?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 Hayo van Loon on Medium]]></title>
        <description><![CDATA[Stories by Hayo van Loon on Medium]]></description>
        <link>https://medium.com/@hayovanloon?source=rss-76b7e7704493------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vX1QXjT0o-eg4Ekx9apPdg.jpeg</url>
            <title>Stories by Hayo van Loon on Medium</title>
            <link>https://medium.com/@hayovanloon?source=rss-76b7e7704493------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 22:18:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hayovanloon/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[Working Around the 9 Minute Limit of Google Cloud Functions]]></title>
            <link>https://medium.com/@hayovanloon/working-around-the-9-minute-limit-of-google-cloud-functions-78ff19bd869c?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/78ff19bd869c</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[serverless-computing]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 17:19:10 GMT</pubDate>
            <atom:updated>2022-02-17T09:02:35.329Z</atom:updated>
            <content:encoded><![CDATA[<h4>Designing a robust system using time-limited compute.</h4><p><em>Update 2022–02–17: Rejoice! Google Cloud Functions (2nd gen) no longer say </em>Ni!<em> after nine minutes. It has been expanded to 60 minutes. So add 51 minutes and read on!</em></p><p>Some things in life are unavoidable; traffic jams, taxes and Google Cloud Function’s nine minute timeouts. Almost as unavoidable are both the question whether there is a way to cheat around the latter and its answer: ‘<em>unlike the first two: no</em>’. The pattern described here might however help you work around the problem a bit.</p><figure><img alt="Sunset on Venice Beach with a man riding a bicycle." src="https://cdn-images-1.medium.com/max/1024/1*M1KlLUcp4wzC-mNUdqqvnQ.jpeg" /><figcaption>Don’t let the sun go down on me.</figcaption></figure><p>Let’s start with a simple example: an alarm clock. Assuming that the alarm is always set far enough in the future, the following function will surely reach the timeout and be killed unceremoniously.</p><pre>func alarm(t time.Time) {<br>   for {<br>      now := time.Now()<br>      if now.After(t) {<br>         fmt.Println(&quot;Beep.&quot;)<br>         break<br>      }<br>      time.Sleep(1 * time.Seconds)<br>   }<br>}</pre><p>But if you know upfront something is likely to happen (we do), you ought to plan for it. This realisation is the easy part. The challenge lies in how you avoid or mitigate the disruptive event while maintaining normal function as much as possible.</p><p>Generically speaking, it starts with detecting or predicting the onset of the disrupting event. For a Cloud Function, this is simple: give or take a few seconds, a timeout will occur at the latest at nine minutes. So we can easily ‘predict’ our event horizon.</p><p>Which brings us to our evasive or mitigating measure. And we are going to make it flashy. Remember <em>&lt;random action movie&gt;</em> where the car is hurdling towards an oncoming truck and the hero(ine) leaps to another car just in time after grabbing <em>&lt;random important item&gt;</em>, <em>*gasp*</em>? That hero(ine) is us and our precious cargo is the input alarm time. We do need an additional medium to pull this off though. We cannot remain tethered to the crashing car, for obvious reasons.</p><p>A direct HTTP call to a new Cloud Function instance would have been that crashing-car tether; once the caller fails, the new instance might also fails in the cascade. In any case: it’s messy. We will use PubSub for decoupling for now, but Cloud Tasks is another good option. We extend the code with a check against a chosen timeout before the real timeout.</p><pre>func alarm(t time.Time) {<br>   timeout := time.Now().Add(8 * time.Minute)<br>   for {<br>      now := time.Now()<br>      if now.After(t) {<br>         fmt.Println(&quot;Beep.&quot;)<br>         break<br>      }<br>      if now.After(timeout) {<br>         republish(t)<br>         log.Print(&quot;timeout reached&quot;)<br>         break<br>      }<br>      time.Sleep(1 * time.Second)<br>   }<br>}</pre><p>Before the real timeout comes to pass, we republish the message and shut down gracefully, wishing the next instance the best of luck.</p><p>Of course, this is a purposely trivial function. What if you would want to have it perform something more complex, like a (long running) computation?</p><p>Let us take for example the partitioning problem[1]. In the partition problem, there is a bookshelf with books of varying number of pages of equal difficulty. In front of the shelf there is a certain number of readers of equal skill. Neither books nor readers may change places and books can only be read in full. The objective is to divide the books over the readers in a way that minimises the (wall clock) time the groups spends reading. With further analysis, it should be clear that spreading the load equally is key here. The problem could be solved with a recursive algorithm like the one below.</p><pre>func solveRecursive(books []int, n, workers int) (int, []int) {<br>   // n is initialised as len(books)<br>   if workers == 1 {<br>      return sum(books, 0, n), []int{0}<br>   }<br>   if n == 1 {<br>      ks := make([]int, workers)<br>      for i := 1; i &lt; workers; i += 1 {<br>         ks[i] = n<br>      }<br>      return books[0], ks<br>   }<br><br>   bestLoss := math.<em>MaxInt64<br>   </em>var positions []int<br>   for i := n; i &gt; 0; i -= 1 {<br>      x, ks := solveRecursive(books, i, workers-1)<br>      acc:= sum(books, i, n)<br>      loss := max(acc, x)<br>      if loss &lt;= bestLoss {<br>         bestLoss = loss<br>         positions = append(ks, i)<br>      }<br>   }</pre><pre>   return bestLoss, positions<br>}</pre><p>By increasing the number of books and the number of readers, execution times will swiftly exceed (any) limit. Results may vary, but on my local machine it exceeded the limit (of my patience) with a random list of 50 books and 10 workers.</p><p>So how can we apply our little pattern here? The short answer is: we cannot (at least, not elegantly). But our goal is solving the problem, not getting a particular solution running. Thus we are allowed to tweak our algorithm, making it at least able to provide intermediate results at a regular pace.</p><p>For this we turn to dynamic programming. I highly recommend reading Skiena’s book on this topic (and the rest of the book as well). For now I crudely summarise it as turning a recursive function inside-out, where the memory footprint is increased for a gain in execution time. Here is a moderately correct implementation.</p><pre>func solveDynamic(xs []int, k int) (int, []int) {<br>   books = xs<br>   workers = k<br>   // use a |xs|*k matrix to memoise losses and positions:<br>   m = initM(books, workers)<br><br>   for w := 1; w &lt; workers; w += 1 {<br>      for b := w; b &lt; len(books); b += 1 {<br>         m[b][w].Loss = math.<em>MaxInt64<br>         </em>acc := 0<br>         for i := b; i &gt;= w; i -= 1 {<br>            acc += books[i]<br>            loss := max(acc, m[i-1][w-1].Loss)<br>            if loss &lt; m[b][w].Loss {<br>               m[b][w] = Cell{Loss: x, Pos: i}<br>            }<br>         }<br>      }<br>   }<br><br>   // reconstruct best scheme<br>   last := m[len(books)-1][workers-1]<br>   positions := make([]int, workers)<br>   positions[workers-1] = last.Pos<br>   for i := workers - 2; i &gt; 0; i -= 1 {<br>      positions[i] = m[positions[i+1]-1][i].Pos<br>   }<br><br>   return last.Loss, positions<br>}</pre><p>Plenty of room for optimisation, but that is not the point. The point is that we can now have intermediate results at nearly any point in time. As a side effect, it runs <em>a lot</em> faster. Even with 5000 books and 50 workers, it completes in seconds rather than minutes. There is probably a lesson in there about first optimising code before throwing tricks or hardware at it, but we will skip that one for now. And for the remainder of this exercise we will increase the problem parameters by a few orders of magnitude.</p><p>Since the data is available throughout the function, we can insert our timeout export at various points. It could look something like this; ‘storeFunc’ would contain the PubSub boilerplate code.</p><pre>func persist(xs []int, workers int, m [][]Cell, w, b int) error {<br>   p := &amp;Problem{<br>      Xs:      xs,<br>      Workers: workers,<br>      State:   &amp;State{M: m, CurrentW: w, CurrentB: b},<br>   }<br>   bs, _ := json.Marshal(p)<br>   return storeFunc(bs)<br>}</pre><p>And we would call it in the inner loop like this (skipping error handling for readability).</p><pre>... (initialisation)</pre><pre>for w := currentW; w &lt; workers; w += 1 {<br>   for b := currentB; b &lt; len(books); b += 1 {<br>      if timeout() {<br>         _ := persist(books, workers, m, w, b)<br>         return 0, nil, nil<br>      }</pre><pre>      ... (the rest)</pre><p>Now all we need to do is initialise the function to use these values (when available) rather than an empty state. That boils down to a simple if-statement.</p><p>But what if our function has dependencies that could somewhat unexpectedly crash (side step: or if we would run on some pre-emptible environment)? We could rely on auto-retry mechanisms, provided the error is non-systematic, but we would still lose all that valuable compute time.</p><p>The answer is using checkpoints. Rather than pushing the state through PubSub, we write the state to a persistent storage. Pretty much any could work; we will use Cloud Storage. With a bit of fancy directory naming, you can create a checkpoint history. This could be the generic structure to aim for.</p><pre>&lt;some bucket&gt;<br>|<br>+-- &lt;unique job name&gt;<br>|   |<br>|   +-- checkpoint-&lt;unix timestamp&gt;<br>|   |   +-- data<br>|   +-- checkpoint-&lt;unix timestamp&gt;<br>|   |   +-- data<br>|   +-- checkpoint-&lt;unix timestamp&gt;<br>|       +-- data<br>...</pre><p>Now when the function is started, it filters the bucket for the job’s checkpoints, sorts them lexicographically and reads the data from the last one. If no checkpoints are found, it will initialise with an empty state.</p><p>The complete main function now looks like this. In the event of a crash or timeout, the amount of compute time lost is always limited to a single algorithm cycle. For readability I left out error handling (always do error handling!), again.</p><pre>func solveDynamic(xs []int, k int) (int, []int) {<br>   books, workers, m, currentW, currentB, err := restore()<br>   if err == ErrNotFound {<br>      books = xs<br>      workers = k<br>      currentW = 1<br>      currentB = 1<br>      m = initM(books, workers)<br>   }<br><br>   lastCheckpoint := time.Now()<br>   for w := currentW; w &lt; workers; w += 1 {      <br>      for b := currentB; b &lt; len(books); b += 1 {<br>         if timeout() {<br>            _ := persist(books, workers, m, w, b)<br>            return 0, nil<br>         } else if checkpoint(lastCheckpoint) {<br>            _ := persist(books, workers, m, w, b)<br>            lastCheckpoint = time.Now()<br>         }<br><br>         m[b][w].Loss = math.<em>MaxInt64<br>         </em>acc := 0<br>         for i := b; i &gt;= w; i -= 1 {<br>            acc += books[i]<br>            x := max(acc, m[i-1][w-1].Loss)<br>            if x &lt; m[b][w].Loss {<br>               m[b][w] = Cell{Loss: x, Pos: i}<br>            }<br>         }<br>      }<br>   }<br><br>   last := m[len(books)-1][workers-1]</pre><pre>   // reconstruct best scheme<br>   positions := make([]int, workers)<br>   positions[workers-1] = last.Pos<br>   for i := workers - 2; i &gt; 0; i -= 1 {<br>      positions[i] = m[positions[i+1]-1][i].Pos<br>   }<br><br>   return last.Loss, positions<br>}</pre><p>And that concludes this little write-up. For certain problems, these patterns should help getting around the nine minute timeout. But although it might have appeared so, we did in fact not ‘conquer time’. We merely bought some extra in exchange for other resources. For instance when cranking the dial up to 50&#39;000 books and 500 workers, each checkpoint was a (non-optimised) 500 MB file. This took a few seconds to write and read, eating into the time available for the actual computation.</p><p>So be critical. Is there no possibility for parallelisation? Could radically redesigning your algorithm not remove the problem for the foreseeable future (like it did here)?</p><p>At some point, you might have to admit that Cloud Functions (or Cloud Run), is no longer the proper fit for your long-running calculations. Maintainability and extensibility are especially likely to yield causes for concern. If and when that time comes, you should consider redesigning your solution around another technology. It really depends on the type of problem, but serverless options include specialised tools like Dataflow, AI Hub or Kubernetes Jobs on GKE or even Cloud Build. Each has its own set of drawbacks and limitations, but what they share, is that they are all (much) more complex to set up and maintain than a simple Cloud Function.</p><p>So for next week’s demo, go see if this little design pattern can help get the job done. And unless you did a successful test run, do not promise you can ‘100x’ the problem just yet.</p><p>[1] Skiena, S.S. (2008), <em>The Algorithm Design Manual (2nd ed.)</em>, Springer-Verlag London Limited, London.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78ff19bd869c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[There Is No ‘Data’]]></title>
            <link>https://medium.com/incentro/there-is-no-data-8ce119f816bc?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ce119f816bc</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[data-democratization]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[it-architecture]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 12:57:01 GMT</pubDate>
            <atom:updated>2021-01-26T12:57:01.662Z</atom:updated>
            <content:encoded><![CDATA[<p>In the early 90’s, corporate IT was invaded by a new tribe: the business intelligence people. Seeking to satisfy their hunger for ‘data’, their tendrils crept deep into existing systems. This often put them at odds with the existing IT teams that had the task of ‘keeping the main show running’.</p><p>Sadly, decades later, this still describes the position of ‘data’ workers in many organisations; invaders in IT. But what if we could start anew? With all our knowledge and experience building IT solutions; with all the currently available (cloud-based) technology? How would we approach this ‘data’? Well first, we would study it a bit.</p><p>We can quickly conclude that data in general have no shape or form. That is a bit of a dead end. So we shift our attention to how it comes into being and how it disappears. In other words, we will start investigating its life cycle and see where that gets us.</p><h4>The Circle of Life</h4><p>Compared to an organism’s, the life cycle of a piece of data is actually pretty simple. Right of the bat, we can exclude a few phases. Data do not die; they just go out of (your) field of view. This is erring on the side of caution. It is much safer than assuming they conveniently disappear. Social media are rife with awkward posts waiting to come back to haunt their authors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5sYT5B7ulxT9hzTQRVTgQ.jpeg" /><figcaption>Aeons later, even the dead can still tell stories (at the LaBrea Tar Pits for instance).</figcaption></figure><p>Data also do not age, go stale or decay. A newspaper issue might be worthless to you in a week’s time, but a historian might <em>love</em> it a century from now. The context determines its value. Personally though, unless I plan on painting the house, my newspapers end up in the paper bin.</p><p>With those out of the way, conveniently few stages remain. Following some business event, a piece of data is <em>produced</em>. Then after some time, this piece of information may or may not be <em>distributed</em>. And since data are inanimate entities, nothing else will happen without some external force.</p><p>We can also pinpoint where this all happens: inside every single application. So if you are in need of some kind of data and you know your application landscape, where would you start looking? The answer should be evident:</p><blockquote>The most natural source for data is the application that produced it.</blockquote><p>Though attractively simple, building upon this two-phase cycle ought to make you feel a wee bit uncomfortable. If nothing happens to the data between production and distribution, sensitive parts will ultimately end up in the wrong places. Even when only distributing to trusted parties, this is a considerable risk.</p><p>Fortunately, the solution is rather simple. Prior to distribution, the pieces of data have to be <em>prepared</em>. You redact (delete, encrypt, hash, …) things like passwords, credit card numbers and personally identifiable information. This phase can also be used to improve data usability by adding extra information. I found that slapping a creation timestamp on every piece often helped solve or prevent all sorts of issues further down the line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9Duazn6E2c-Gu3Vrk6thSQ.png" /></figure><p>The actions taken in the preparation phase, combined with a well-maintained distribution list, should keep things on the safe side, legally and otherwise. Let us shift our focus to the distribution a bit more.</p><p>When you think of distribution, you think of an active process; for instance newspapers that get delivered to your doorstep. So if you want promote usage and experimentation with data, why not design a flexible system for distributing it? Fortunately, we can adopt a solution from the real world: subscriptions. We will make interested parties sign up for subscriptions at the source application. From there, the sign-ups can be judged by its application managers — they ought to know best who to allow access.</p><p>You could also assign roles to (groups of) subscribers. These roles can be used to tailor the data preparation in the preparation phase. And since the sign-up process is awfully generic, we can (and should) also standardise it across our application landscape for both greater efficiency and ease of use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*dnTyVXeaPgKHgHBDGuLV-Q.png" /><figcaption>An application that pushes data as a side-effect of handling ‘normal’ API calls</figcaption></figure><h4>Pushing for Simplicity</h4><p>But why do we go for a newspaper-like subscription model? Why not a library subscription model where subscribers can walk in and browse at their leisure? Isn’t that easier to implement?</p><p>Pushing data might sound like a lot of work (it’s not), but it is essential in simplifying the entire system. It allows us to introduce the following rule:</p><blockquote>Once data has been pushed into a subscriber-provided channel, it is no longer the responsibility of the producer.</blockquote><p>A channel is a general term for both streaming and batch communication channels (message queues, file dumps). If we then add that (allowing access to) the receiving channel is the responsibility of the subscriber, the entire data flow is covered.</p><p>The main reason for this exercise is to free producer applications from any (external) burdens tied to historical data, like random query access. Once the data have been pushed, it’s done (produce, push, done). It brings the entire process more in line with a normal web API flow (request, reply, done). In fact, it blends in rather well with other API specifications:</p><pre>// Fetch a single book by name<br>GET  /v1/books/&lt;name&gt;</pre><pre>// Fetch a list of books<br>GET  /v1/books</pre><pre>// Receive updates on books<br>POST /v1/books:subscribe</pre><p>Like normal API calls, changing requirements might force you to create a new version at some point. This too follows an age-old pattern: develop (beta), use, deprecate, drop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IYMSA_7fpFa7veFEWDeetQ.jpeg" /><figcaption>Tar pits are lakes bubbling with history. But they are not necessarily an asset to every garden.</figcaption></figure><h4>History? Dashboards? Analytics?</h4><p>But what about all that ‘precious’ historical data? Well, that is up to the parties that actually see value in it. The principle is once again simple: <em>“You want it? You pay for it.”</em>. Since the value of data is context-dependent, it is hardly fair to burden someone who is not necessarily interested (the producer) with the costs. To be clear: these are hardly for storage, but rather for query access and maintenance.</p><p>So if someone is interested in historical data, they can subscribe to its feed. They can then transform its output at their leisure before storing it as history. The need for ad hoc historical data access could also be pooled. Typical use cases would be analytics and mitigating cold-start in machine learning. And of course, access to historical data is pretty much a must-have when a data subscriber has to recover from an outage in its incoming data channels.</p><p>For all this, you would just create a special application. It would be subscribed to all the relevant feeds to build histories for each. Perhaps ‘data warehouse’ would be a good name for it. Maybe do a few extra transformations and plug your dashboarding and analytics tools somewhere into it as well. Important caveat: the data in the warehouse must have the same access rules as their source applications, lest you risk a data leak. Use with caution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpWdwEckavovFhKuCdFiQA.jpeg" /><figcaption>Take-away time!</figcaption></figure><h4>Synthesis</h4><p>And with that, we should have ticked all major boxes on ‘data’. From this point of view, there really should not be that much special about it. In part it is just another method for accessing ‘normal’ application data. And to make it so, modern tools in the form of managed cloud services (like Google Pubsub, AWS SQS, …) can greatly reduce development time and effort.</p><p>Of course, unless you have a greenfield situation, you will be haunted by the ghosts of IT past; legacy systems, vendor software with poor data interfaces and so on. But these should be addressed in steps on the path towards, rather than compromises on, the synthesis of ‘data’ and IT. Defining a strategy is way beyond the scope of this post, but could contain terms like: shared principles and rules, developer autonomy and decentralisation.</p><p>If you really want to make use of ‘data’, there should ultimately be no ‘data’. Either you fully integrate it into everyday IT, or you perpetuate a three decade old workaround. Your choice.</p><h4>PS. Before We Forget…</h4><p>Earlier I mentioned that data do not die. How does this align with the ‘right to be forgotten’, which has been anchored into legislation in many countries? First of all, the easiest way to comply is to redact (hash, encrypt, …) sensitive elements of data prior to distribution. But sometimes this is just not feasible or sufficient. So how to handle a request to be forgotten? The data subscription system will help us. We will start with purging the offending data at the source application. Then we go through its subscription list, looking for subscribers that might have received the data and repeat the purge there. A process we repeat as long as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ce119f816bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incentro/there-is-no-data-8ce119f816bc">There Is No ‘Data’</a> was originally published in <a href="https://medium.com/incentro">incentro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Data Democracy]]></title>
            <link>https://medium.com/incentro/demystifying-data-democracy-e6e097be9bfe?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e097be9bfe</guid>
            <category><![CDATA[digital-transformation]]></category>
            <category><![CDATA[data-democracy]]></category>
            <category><![CDATA[enterprise-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 08:07:20 GMT</pubDate>
            <atom:updated>2020-10-19T08:07:20.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Big Data. Agile/Scrum. Machine Learning. DevOps. Smart Algorithms. Artificial Intelligence. Business IT sure loves its fuzzy buzz-words. Some of the latest rising stars are ‘data democratisation’ and its slightly more daunting sibling ‘AI democratisation’.</p><p>What all these buzz-words have in common is that, when facing an unsuspecting audience, inserting them in a sentence will make one look smart, agile and DevOps. This makes them an invaluable tool in any consultant’s toolbox. What they also have in common is that many (of said consultants) will remain awfully vague or evasive when pressed about what it actually means. Which is a pity, because underneath all the hype, there is substance to be found.</p><p>So for the first of those new kids on the block, allow me to paint a more tangible picture; what data democratisation could actually look like. I will even do better than that. In future posts, I will even outline strategies and architectures for achieving it. The other kid, AI democratisation, is for a large part about bringing accessible tools to data, so it is natural a next step.</p><p>To understand data democratisation, we need to go back to the root of the term: democratisation.</p><blockquote>Democratisation could be defined as the process where the power is shifted from the small elite to the many. In a broader sense, it can be seen as a process of decentralisation.</blockquote><p>Data democratisation is not the first non-political democratisation. Not too long ago, television (also known as: that odd, hardly interactive Netflix) was a scarce commodity. People would go to theatres or group up at early-adopting neighbours to watch it. But eventually most people got their own (black-and-white) television sets. And for the first time in history, people could experience, right in their living room, events taking place hundreds of miles away, as if they happened yesterday. Yes, yesterday, because it was still a long time ago. But once again: decentralisation.</p><figure><img alt="Crowd watching television" src="https://cdn-images-1.medium.com/max/800/1*h8v3PSlchPqw7EFb8ByQeg.jpeg" /><figcaption>“Crowd Watching Television at Kings Cross” by “Australian Broadcasting Corporation” licensed under <a href="https://creativecommons.org/licenses/by-nd/2.0/">CC BY-ND 2.0</a></figcaption></figure><p>Which brings us to data democratisation. What does it look like?</p><blockquote>Data democracy should be like switching on the television and tuning into its channels. Multiple at the same time if you so desire and either in (big) batches or streaming.</blockquote><p>Subscribe to a channel, get your data, do your analysis and cancel the subscription. Or leave it running for recurrent analyses. Subscribe to one or more streaming channels, add a twist of your own (like, gasp, machine learning) and publish it as a channel of its own. Or subscribe to some channel to receive its data in a simple spreadsheet every day. In short: consume and publish data as your needs require.</p><p>So where do people in a data democracy so conveniently get their data from? Where do they apply for those subscriptions? Well, that is simple: straight from the source, the data producing applications. You do not want or need intermediary stations. These must be maintained and could potentially distort data — the whisper game.</p><blockquote>A data democracy lives by the principle that if you produce and therefore own the master data, you must also provide reasonable access to interested, <em>properly authorised</em> consumers.</blockquote><p>This implies a profound change in the enterprise. Like with a real democracy, it not simply building a house of parliament. Nor subsequently stuffing people in there with the label ‘representatives of the people’. Nor telling them that they are the new rulers now. The (real) people would neither understand nor acknowledge it. And without buy-in, members of the old regime would try to marginalise it or tear it down as soon as they could.</p><blockquote>Like a real democracy, establishing a data democracy requires breaking up and redefining existing structures.</blockquote><p>In that light, the transition into a data democracy could be seen as a revolution. But not all revolutions are violent or abrupt. Silent, grass-roots revolutions might not be flashy, they might (appear to) take some time, but they make less victims and their effects tend to be longer lasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*sBcoXJ9j_K1i99pzmvMKHw.png" /><figcaption>Building block: the ‘extended service pattern’. All components serverless and on commoditised services.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e097be9bfe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incentro/demystifying-data-democracy-e6e097be9bfe">Demystifying Data Democracy</a> was originally published in <a href="https://medium.com/incentro">incentro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Like Google]]></title>
            <link>https://medium.com/incentro/building-like-google-3c539546dc61?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c539546dc61</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[happiness]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[cloud-architecture]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Sun, 09 Feb 2020 14:19:27 GMT</pubDate>
            <atom:updated>2020-02-09T14:19:27.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>Discovering How to Build Solutions When You Are Not Google</h4><p>I must admit, I have somewhat of an odd hobby. Although for some my walking uphill with a snowboard might qualify, that is not the one I am aiming at today. No, I like discovering and applying the principles by which, I think, Google develops software.</p><p>But this hobby is hampered by two problems. One: I do not, nor ever did, work at Google. So I was never surrounded by senior engineers that would patiently teach me (or company chefs serving awesome lunches daily). Two: my customers are usually not Google, which brings another set of limitations (and less fancy lunches).</p><p>The largest (and arguably most exciting) part of my hobby revolves around reverse designing Google’s workflow. To this end I read (between the lines of) their blogs, observe systems and tools they release in Google Cloud and analyse the structure of (open source) code they write. I try to discern that grand unifying principle, if there is one to be found. And I think I might be on the right track.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbqGKvHauLBEeQd8AcjZFw.jpeg" /></figure><p>But in the second part of my little hobby, applying those principles, I still run into the other problem. Because one downside of neither me nor my customers being Google, is that we have considerably fewer resources. Now when I say resources, you might immediately think of the raw computational power of their data centres, or the enormous collection of quality data therein.</p><p>But provided there is value in a computationally demanding workload, elastic public clouds can accommodate for the former. And while the latter is definitely more difficult to match, data in and of themselves do nothing. No, I primarily think of the disparity in human resources; the skilled professionals that do the work. Here are two simple examples to illustrate my point.</p><p>On the application level, we non-Googlers have all kinds of unstable, faulty legacy software that feeds us data in obsolete formats through cumbersome means. Yes, I am looking at you, nasty SOAP XML interfaces. And even when we choose to ignore (generally sensible) guidelines like ‘minimise investments in legacy’, we still would not have the people available to (reasonably) swiftly perform the required changes. We have to make do.</p><p>On the security level, while we we may have security and penetration testing teams, they are not on the same level as aforementioned company. So to keep things reasonably secure, we run our (legacy) backend application servers in private, segregated networks shielded by firewalls. We then pray that no one manages to get into those as he or she would be shooting fish in a barrel.</p><p>So things might seem pretty bleak. But when I started with developing on Google Cloud late 2015 (incidentally kick-starting this odd hobby of mine), hope sparked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GeDX0jamNhbTDotvI-99kQ.jpeg" /><figcaption>This particular ray of hope did not last. It was followed by a restless night in a mountain cabin and a trundle back down through clouds and fog the next day. But overal we had a good time.</figcaption></figure><p>Back in those days (feels like ages), Google Cloud was a pretty spartan affair. We had basic VMs, AppEngine, BigQuery, Blob Storage and a handful of other services. We did not even have any kind of managed Hadoop. Life was simpler, but we were happy. For the sake of accuracy though, do replace ‘life’ with ‘documentation’ and ‘simpler’ with ‘spotty’.</p><p>But thanks to this frugality, I was able to discern a system, a pattern. Google Cloud has always had a strong offer of managed services, dubbed platform-as-a-service (or PaaS). Developers can simply push code to these services and receive web servers, big data pipelines and such in return. These will operate according to professional (reliability, security, et cetera) standards without involvement of any system operator.</p><p>I noticed that each of these PaaS services could be plotted somewhere in what I now like to call the technology triangle of compute, storage and transfer. But more often then not, they would reside in the corners of a triangle; they only took care of one concern. AppEngine only provided a web server (compute). Datastore only provided quick read-write storage. PubSub only moved data around (transfer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*iTsxXJmK1hOB0n0weAN2iA.png" /><figcaption>Just a few (half?) of the services available back then. Nowadays Google Cloud has much more services. Where should for instance AutoML Tables be plotted?</figcaption></figure><p>Combining services from across the triangle, I could quite rapidly build scalable and maintainable (and secure) landscapes, all by my little self. The need to include several different services to achieve things other technologies provided as a one-stop-shop initially seemed inconvenient. But I quickly realised, and leveraged, its value. I could nimbly swap or add components or services as requirements changed.</p><p>If I for instance was using BigQuery for storage and real-time access became necessary, adding a simple write to Datastore would make that happen. However, unlike BigQuery, Datastore does not do compute. So while I could subsequently implement a data transformation pipeline in BigQuery using just queries, I could not do so in Datastore. There are plenty of solutions to this ‘problem’; the point I am trying to make is that the further a technology is from a corner, the harder it can be to replace. Plotting technologies in the triangle can make you better aware of this, aiding your decision making.</p><p>But the triangle does not capture another, important dimension of good design. This one was taught to me (rather explicitly) as I was introduced to Google Cloud and platform-as-a-service. Because it was all about layering; software-as-a-service on top platform-as-a-service on top of infrastructure-as-a-service. I now apply a similar layering scheme to any system I analyse or design. From bottom to up: infrastructure (VMs and networking), application (web services, databases, applications) and business (people using applications). Like with the OSI model, each layer extends on what is provided by a lower layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r3V7S8SaSZjz2dNSTVTvYA.jpeg" /><figcaption>Some layers are seasonal — roughly same location as main photo (in Arolla, CH).</figcaption></figure><p>You could also insert extra layers; for instance platforms like Kubernetes and Hadoop. These tend to reside between infrastructure and application. When plotted in my technology triangle, they would likely end up in the centre; they could provide everything, often doing so in a reasonably well integrated fashion. But for setting up and maintaining these on a professional level, you do require people with specialised skill sets. This combination of benefits and investments can often make migrating to and from them non-trivial (aka: lock-in). Do note that paradoxically Kubernetes <em>does</em> decrease lock-in with infrastructure providers (clouds) or hardware suppliers.</p><p>A final ingredient to the mix is to design for and with microservices. A paradigm shift that has been hard to miss, regardless of whether you were following Google or not. Unlike with monolithic applications, developers in microservice landscapes do not need to concern themselves too much with negatively impacting or getting impacted by other parts of the application. Their microservice <em>is</em> the entire application and as long as it fulfils its contracts with its downstream clients and upstream services, everything should be peachy.</p><p>This, once again, is a separation of concerns. But now it is horizontally across (business) features or services rather than vertically, as with the technology stack. You could plot them together in a grid where the services form the capstones of the technology stacks. We can even fit software-as-a-service solutions (like for instance G-Suite) in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*D1Pnl-2mbhtcWDbXzrEvvQ.png" /><figcaption>Separation of concerns in two dimensions. Green and red require your attention. Orange just your money. S<em>implified. Not to scale.</em></figcaption></figure><p>So separation of concerns is going to be our theme. Because no one is an expert at everything. Not being Google, at times we might even struggle to get sufficient people to handle basic hygiene (like system maintenance). We must then force such vital roles upon the people we have available. But developers often do not like to nor are they good at maintaining VMs (or fixing computers). Data scientists do not like to be doubling as database administrators (or computer fixers). And system operators probably do not care much for implementing business logic (but they might like fixing your computer —higher chances if it runs on Linux).</p><p>I believe that people are happiest when they can do their own thing. The thing or things they like doing and (consequently?) are good at. So let us prevent placing ourselves in situations where we need to foist chores upon our fellow engineers (or ‘underlings’ if you so prefer). Carefully decompose your problem into distinct functions. Carefully design those functions with plugable compute, storage, and transfer technologies in mind. And then carefully select infrastructure or platform-as-a-service to match your <em>current </em>talent pool.</p><p>To me building like Google is about enabling engineers to focus on building the parts they like to build. You do not need to be Google to achieve that. So let’s start making it happen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c539546dc61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incentro/building-like-google-3c539546dc61">Building Like Google</a> was originally published in <a href="https://medium.com/incentro">incentro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Joining the Coders Without Borders]]></title>
            <link>https://medium.com/incentro/joining-the-coders-without-borders-84cf1128542a?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/84cf1128542a</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[flexibility]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Fri, 23 Aug 2019 20:51:51 GMT</pubDate>
            <atom:updated>2019-08-23T20:51:51.935Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or: How to Always Get the Best Tools for the Job</h4><p>Ever been in the situation where there is a good framework, but it hasn’t been ported to a language you know (i.e. Python’s scikit-learn)? Or where there is a port to your language, but it lags behind several months or years its native language (i.e. Apache Beam Python vs Java)?</p><p>Fortunately, I am reasonably proficient with mentioned languages, so these examples do not directly apply to myself. But there are (probably) plenty of useful frameworks out there for which I do not (yet) master the native language. Regardless, when you work in teams, you might run into the issue by proxy if some team members do not know a framework’s native language.</p><p>Other than waiting and hoping, there does not seem to be a whole lot that can be done about it. Until you rewrite the rules of the game that is. “If the mountain does not come to Muhammad, then Muhammad must go to the mountain.”[1]: you just learn the language!</p><p>This may sound irrelevant in a professional setting, but I would argue that you could make a business case for it. With the benefit of being able to choose the best tools (and up-skill your developers), the costs are the developer time alternative costs. Learning time for any language to a basic professional level is measured in weeks, not months or years. It usually takes more time for updates to trickle down from the framework’s native language to yours.</p><p>Also, in a world moving towards microservices, one is less bound by old constraints of languages. As long as a microservice fulfils its contract (and security is in order)(and resource use is within limits), what language it is written in should be the least of concerns. Plus, if you keep your services micro enough, coding them in the first place should be less daunting in any case.</p><p>Last year, I started learning Go and recently I started with C. I could not help notice that I was following a similar pattern. So without further ado, here I present my free, seven-step, (partly) tongue-in-cheek guide to learning new programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yit6WMVMTP8l9mZe9bD7MA.jpeg" /></figure><h3>Step 1: Best! Language! Ever!!1!</h3><p>Face it: your to-be-learned language is better than any language you have ever learned. Its performance is stellar, it is incredibly concise, it is the source of all life. Be sure to inform co-workers and bosses of your plans. Make sure they acknowledge the aforementioned absolute truths. At times this might require application of minor force, but ultimately it is for their own good. Some might even want to join you in your quest; the more, the merrier.</p><h3>Step 2: Hello World</h3><p>Only after you have raised expectations sky high should you try your hand at ‘Hello World’. This requires patience, but once you start receiving the first (passive-aggressive) enquiries on your progress, you are good to go.</p><p>For C, I could quite literally code <em>the</em> ‘Hello World’ [2]. You will probably have to make do with a puny imitation. But go code it all the same.</p><pre>#include &lt;stdio.h&gt;</pre><pre>void main() {<br>        printf(&quot;hello, world&quot;);<br>} </pre><p>Compile it (if applicable).</p><pre>$ gcc -o helloworld helloworld.c</pre><p>Run it.</p><pre>$ ./helloworld<br>hello, world</pre><p>Weep tears of joy and show this masterpiece to <em>all</em> your colleagues. They might appear underwhelmed, but do no be disheartened. Those are cheap facades for their raging envy. If needed, extrapolate the features of this fine piece of software engineering to <em>all </em>the benefits lectured to them during step 1. To your trained eye, these are of course obvious and justified, but not all eyes are equally susceptible to the truth.</p><h3>Step 3: Read</h3><p>Once you have those bare basics, you will need practice. But first you will need to get familiar with the features of the language and its idioms. Try to get a basic grasp of the language’s main concepts. Most languages loudly advertise those somewhere on the internet. With any luck, they may host some small tutorials as well. Have a Go! (pun intended)</p><p>Learning to write proper, idiomatic code can take quite some time. Reading a code style guide from a respectable authority on the matter should give you a head start. Besides, it is never a bad thing to read stuff from people you are soon going to be rubbing elbows with. For my language, I scanned through the Linux Kernel Coding Style[3].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glxNOYrWBPn8Zwfkz0rhOw.jpeg" /><figcaption>Learning about food safety equipment</figcaption></figure><h3>Step 4: Solve a Classical Problem</h3><p>You could try to implement that awesome app you thought up the other day, but restrain yourself for now. Keep it pure; make it about just you, the language and writing it properly. The value here is in the journey, not in the result.</p><p>My advise is to solve some standard coding problem you have already solved in another language. You should pick one of reasonable complexity. For reasons I will detail below, I always pick a variation of the coin change problem[4]: “Given an infinite supply of coins from a certain set of values, what is the minimum number of coins required to obtain a certain target amount”.</p><p>I found that when solving this issue, you encounter several basic language components like flow control and collections. Especially with the latter, form and ease of use can vary (surprisingly) from one language to another. This is where the caveat comes though. Whenever you run into an issue, do not go to StackOverflow to look for a quick fix. Rather, use StackOverflow to (find references to) read up on the topic at hand. Then and only then return to the issue at hand. You learn the most from questions you both ask and answer yourself.</p><p>Another plus of the coin problem is that it can be extended naturally in several ways. If you had not done so already, you can implement using command line arguments as input for both the target amount and value set. This can help you bump into things like number parsing and exception handling.</p><p>For this particular problem, you may also want to implement your own sorting algorithm along the way. Another tweak is to add the requirement to <em>elegantly</em> return not only the minimum number of coins, but the underlying set of coins as well. Not all languages have convenient support for returning tuples. Or even collections.</p><h3>Step 5: Include an External Library</h3><p>Real-life programming usually revolves around tying one library to another with as little code as possible. More often than not, these libraries are not part of the language’s built-in libraries. Therefore it is imperative to find out how to include external libraries. Pick something simple to practice; for instance a single-purpose library like a JSON or YAML parser. Anything will do really, as long as it does not distract you from the language; time spent configuring peripherals is time not spent learning the language.</p><h3>Step 6: Go Parallel</h3><p>Eventually you will need to do some parallel processing, for instance when aggregating information from multiple web services. I have yet to encounter two languages that handle or even let you express such concepts in a similar fashion. At times it may take you (deep) into the bowels of the language and/or your operating system. Fun stuff. You can opt to skip this step for now though, it doesn’t really matter as the next step is …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPUZ0ySf8q0y_LrEAO8D0w.jpeg" /></figure><h3>Step 7: Despair</h3><p>Even when implementing simple stuff, you still visit StackOverflow at the wing-flapping rate of a hummingbird. Your compilation error logs dwarf Wikipedia. At times your programs crash before you even write them. Although you may have experienced some improvement since HelloWorld, you are nowhere near as productive as in your previous life. You are starting to realise it is going to take weeks if not months to reach a base professional level with your new darling.</p><p>But do not give up. No one ever said it was going to be easy (Did I happen to give that impression? My bad). Take a few hours every week to try and build something small, something funny: prime content for banter at the coffee machine. Also: read up on gRPC[5], which can help build language agnostic microservice landscapes. And who knows? Maybe you will get that chance to replace or build a microservice in that fancy new language.</p><p>So just keep coding, keep learning and keep testing, everything.</p><h3>Links</h3><p>[1] The Phrase Finder, “If the mountain will not come to Muhammad…”, <em>The Phrase Finder</em>, 2019. Available: https://www.phrases.org.uk/meanings/if-the-mountain-will-not-come-to-muhammad.html [Accessed Jul 27, 2019]</p><p>[2] Wikipedia contributors, “Hello World”, <em>Wikipedia.org</em>, 2019. Available: <a href="https://en.wikipedia.org/wiki/%22Hello,_World!%22_program">https://en.wikipedia.org/wiki/%22Hello,_World!%22_program</a> [Accessed Jul. 27, 2019]</p><p>[3] The kernel development community, “Linux kernel coding style”, <em>The kernel development community</em>, 2016. Available: <a href="https://www.kernel.org/doc/html/v4.10/process/coding-style.html">https://www.kernel.org/doc/html/v4.10/process/coding-style.html</a> [Accessed Jul. 27, 2019]</p><p>[4] Project Euler, “”, <em>The Project Euler</em>, 2019. Available: <a href="https://projecteuler.net/problem=31">https://projecteuler.net/problem=31</a> [Accessed Jul. 27, 2019]</p><p>[5] gRPC contributors, “”, <em>gRPC: A high performance, open-source universal RPC framework</em>, 2019. Available: <a href="https://projecteuler.net/problem=31">https://grpc.io</a> [Accessed Aug. 23, 2019]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84cf1128542a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incentro/joining-the-coders-without-borders-84cf1128542a">Joining the Coders Without Borders</a> was originally published in <a href="https://medium.com/incentro">incentro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing And Building An Event Tracking Backend with BigQuery]]></title>
            <link>https://medium.com/incentro/designing-and-building-an-event-tracking-backend-with-bigquery-1ad06a8985f9?source=rss-76b7e7704493------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ad06a8985f9</guid>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[app-engine]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Hayo van Loon]]></dc:creator>
            <pubDate>Sat, 16 Feb 2019 15:37:27 GMT</pubDate>
            <atom:updated>2019-02-16T15:37:27.715Z</atom:updated>
            <content:encoded><![CDATA[<p>Comprehensive event tracking data in business analytics has become pretty common. Where for a long time event data was nearly synonymous with website click-stream data, it has now found uses in plenty of other areas (e-mail tracking, <em>*cough*</em> internet-of-things). There are several off-the-shelf offerings that help you store and prep data for analysis, but building your own solution might be easier than you think.</p><p>In this post I will walk through designing and building a real-time solution on top of Google’s Magical Data Warehouse of Wonders, more commonly known as BigQuery. With only (auto-)scalable components, the solution can start small, growing (and shrinking) as volume and throughput demand. The data source can be any application that is able to push data tagged with a user ID; so my scope here is getting those data stored and ready for analysis.</p><p>For this exercise we will be helping fictional Bob’s fictional company, “Bob’s Knob Shops”, with handling its click-stream data. Bob’s empire spans several shops, loosely matching knob type families. His customers live on every continent (including Antarctica) and his company never sleeps. Bob craves insight into user behaviour on his web shops. The event data from Bob’s site is limited to a timestamp, id, time zone, URL and referrer URL. These data are always both impeccably well-formed and semantically valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2lJdPtOf1vxgKIhxVUMlw.jpeg" /></figure><h3>Onwards!</h3><p>Specifying a data schema that matches your data access patterns is important for many database solutions and BigQuery is no exception. BigQuery is a column store and works best when the data are: 1) denormalised and 2) stored in a single table.</p><p>Storing all the data in a single table might seem troublesome, but BigQuery’s column types include arrays (lists) and structs (objects). This enables you to include data you would otherwise store in auxiliary tables. In doing so, you avoid the need for JOIN operations on (potentially) billions of rows.</p><p>Another best practice is to cluster your data (I strongly recommend reading Felipe Hoffa’s post [<a href="https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b">1</a>] on it). Functionally transparent, data clustering will cause BigQuery to store related rows in close proximity. This can have profound beneficial effects on performance, and thus, costs[<a href="https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b">1</a>]. So let’s use that as well.</p><p>The resulting table creation query would look like something like this. The data will be partitioned by date and clustered by channel (shop type) because Bob likes typically likes his statistics by channel and then by user — <em>know your data access patterns</em>.</p><pre>CREATE TABLE `bobs_knob_shops.sessions` (<br>  channel_id STRING,<br>  visitor_id STRING,<br>  timezone_offset INT64,<br>  start_time TIMESTAMP,<br>  end_time TIMESTAMP,<br>  hit_count INT64,<br>  hits ARRAY&lt;STRUCT&lt; <br>    timestamp TIMESTAMP,<br>    url STRING,<br>    referrer_url STRING <br>  &gt;&gt;)<br>PARTITION BY<br>  DATE(start_time)<br>CLUSTER BY<br>  channel_id,<br>  visitor_id</pre><p>Marvellous. And now we hit our first snag. Below is an example event message and if you take a step back, you might spot the problem. (There is nothing wrong with this data or its format.)</p><pre>{<br>  &quot;channel_id&quot;: &quot;bobs-door-knobs&quot;,<br>  &quot;visitor_id&quot;: &quot;visitor1&quot;,<br>  &quot;timestamp&quot;: &quot;1544896138528&quot;,<br>  &quot;timezone_offset&quot;: -60,<br>  &quot;url&quot;: &quot;<a href="https://door.knobsfrombobs.za/product/123456-78">https://door.knobsfrombobs.za/product/123456-78</a>&quot;,<br>  &quot;referrer_url&quot;: &quot;<a href="https://door.knobsfrombobs.za/lister/cellar">https://door.knobsfrombobs.za/lister/cellar</a>&quot;<br>}</pre><p>The issue is that we receive single events, whereas we designed our rows to be complete sessions. In practice, this would mean that rather than appending a new row, we would need to update part of an existing one (unless it is the first in the session). And updating rows, while possible, is not something BigQuery was designed to do. Updating rows is a rather expensive operation; it runs through all the bytes in the table. To add insult to injury, you cannot run multiple updates on the same table in parallel.</p><h3>Getting Back On Track</h3><p>We could use an additional technology, like Apache Beam, to aggregate events into sessions and trigger a write to BigQuery once a session has concluded. For our use case however, this is not needed. We will use an unaggregated flat table for our events and ship them over into the final sessions table every so often.</p><p>This ties in nicely with a closing note in Felipe Hoffa’s post[<a href="https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b">1</a>]. He mentions that inserting data at multiple times during a day will weaken the clustering. So using a single table would have never been a good idea (and yes, that would have been an issue for the Beam job as well).</p><p>Hence we will use an additional table it is and copy it over every night. We will use the UTC time zone, which is the default for Google Cloud, to determine midnight. It is best to be explicit about time zones, but this way the punishment for accidental omission is less severe (or even present). We will skip clustering and partitioning; we do not expect to query this table a lot and it will contain at most a single day of data.</p><pre>CREATE TABLE `bobs_knob_shops.events` ( <br>  channel_id STRING,<br>  visitor_id STRING,<br>  timestamp TIMESTAMP,<br>  timezone_offset INT64,<br>  url STRING,<br>  referrer_url STRING<br>)</pre><p>Don’t you love late night online knob shopping sprees? Alice sure does. Charles not so much, but he lives in a wildly different time zone. You might have already guessed it: job that simply copies over all the data in the daily table would leave you with broken sessions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QllI2TwSKHqRxmAGivH9Ug.jpeg" /></figure><h3>The Devil is in the Details</h3><p>So we need to be smarter. Also note that while this daily job is running, new events will keep pouring in. And deleting the rows after they have been inserted into the aggregated table? Another expensive, semi-blocking operation for BigQuery.</p><p>The solution is to use two unaggregated tables: one for the even days, another for the odd. Writing is only done in the active table, which at the turn of midnight, will become the inactive table. Then all we need to do is:</p><ul><li>aggregate events into sessions (for sessions that have been concluded) and insert those into our final sessions table,</li><li>insert non-concluded sessions events into the active table and</li><li>truncate the inactive table</li></ul><p>Two more queries and Bob’s your uncle. Our first task is to identify closed sessions. We will need to define a rule for this; we will go with “<em>a session is considered closed when no new events have been detected for a user for two hours</em>”.</p><p>Applying this rule, we could run the job at midnight and add a clause filtering out all sessions which had events passed 22:00 h. While this would work, it would delay sessions ending well before midnight by 24 hours. That will cause inconsistencies in day-to-day reports. Quick fix: we run the job (at least) two hours after midnight on a union of both tables.</p><pre>INSERT INTO `bobs_knob_shops.sessions` (<br>  channel_id, visitor_id, timezone_offset, start_time, end_time,<br>  hit_count, hits<br>)<br>SELECT<br>  channel_id,<br>  visitor_id,<br>  MAX(timezone_offset) timezone_offset,<br>  MIN(timestamp) start_time,<br>  MAX(timestamp) end_time,<br>  COUNT(1) hit_count,<br>  ARRAY_AGG(STRUCT(<br>    timestamp AS timestamp,<br>    url AS url,<br>    referrer_url AS referrer_url<br>  ) ORDER BY timestamp) hits<br>FROM (<br>  SELECT<br>    *,<br>    MAX(timestamp) OVER (PARTITION BY visitor_id) last_timestamp<br>  FROM<br>    `bobs_knob_shops.events_*` )<br>WHERE<br>  last_timestamp &lt;= TIMESTAMP(CURRENT_DATE())<br>GROUP BY<br>  channel_id,<br>  visitor_id</pre><p>Of course, the logic in the query for the cross-midnight sessions complements this one. There is however a small challenge: we cannot capture our table selection logic into BigQuery SQL (as of time of writing). So we will make it a simple select query and handle the data destination in the controlling application.</p><pre>INSERT INTO `{}` (<br>  channel_id, visitor_id, timestamp, timezone_offset,<br>  url, referrer_url<br>)<br>SELECT<br>  channel_id,<br>  visitor_id,<br>  timestamp,<br>  timezone_offset,<br>  url,<br>  referrer_url<br>FROM (<br>  SELECT<br>    *,<br>    MAX(timestamp) OVER (PARTITION BY visitor_id) last_timestamp<br>  FROM<br>    `bobs_knob_shops.events_*` )<br>WHERE<br>  timestamp &lt; TIMESTAMP(CURRENT_DATE())<br>  AND last_timestamp &gt;= TIMESTAMP(CURRENT_DATE())</pre><h3>Tying It All Together</h3><p>The final task is to truncate the inactive table. This is handled via two simple API calls: delete and create. We can use a simple AppEngine to act as our workflow manager; it has cron tab functionality to boot. We will also use it as our event-receiving API back-end.</p><p>Given that there are Google Client APIs available for all standard AppEngines, you are free to choose your favourite language. Here I will use Python.</p><pre># insert all closed sessions<br>client.query(AGGREGATION_QUERY)<br><br># copy the rest to current event table<br>current = DAILIES[(days_since_epoch()) % 2]<br>client.query(LEFTOVER_QUERY.format(for_query(current)))<br><br># truncate old table<br>previous = DAILIES[(days_since_epoch() + 1) % 2]<br>client.delete_table(previous)<br>client.query(CREATE_EVENTS_QUERY.format(for_query(previous)))</pre><p>The (BigQuery) client calls should speak for themselves. They execute the queries mentioned earlier — after a little bit of string replacement.</p><p>I used a two-item list with the event table references (‘DAILIES’) and alternate between them using the number of days since January 1st, 1970. Using the day-of-year will cause trouble at year boundaries.</p><p>Inserting events into the tables uses the same table reference trick and is, by nature, even simpler.</p><pre>row = request.json<br>table = client.get_table(DAILIES[days_since_epoch() % 2])<br>client.insert_rows(table, row)</pre><h3>Closing Notes</h3><p>The logic described here should get your little event tracking system running. However, you will need to take additional measures before it can properly be released into production.</p><p>On the legal side of things there are regulations regarding the collection and storage of personal data. To be compliant with Europe’s GDPR laws[<a href="https://ec.europa.eu/info/law/law-topic/data-protection_en">2</a>], you might need to set up a workflow for deleting personal user data.</p><p>Continuing with the technical side, I assumed receiving perfectly valid and well-formed data.The flow in general is pretty happy-sunshine. So you might want to add some checks, logging and retry logic.</p><p>More importantly however, I also skipped over secured access and authentication. Though not necessarily an issue on the event-receiving endpoint, allowing unauthenticated users to freely trigger the aggregation workflow will have dire consequences for the system.</p><p>Fortunately, there are several ways to secure your AppEngine, depending on your flavour and version. So read up, get coding and, never forget, keep testing.</p><h3>P. S.</h3><p>The full demo code is available on my GitHub (<a href="https://github.com/HayoVanLoon/tracking-backend">link</a>). Some logic was added for the sake of generalisation. It also includes a basic OAuth2 authentication flow.</p><h3>Links</h3><p>[1] Filipe Hoffa<em>, </em>“Optimizing BigQuery: Cluster your tables”<em>, Medium.com</em>, 2018<em>. </em>[Online]<em>.</em> Available: <a href="https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b">https://medium.com/google-cloud/bigquery-optimized-cluster-your-tables-65e2f684594b</a> [Accessed Jan. 30, 2019]</p><p>[2] European Commission, “Data Protection”, <em>European Commission Website</em>, 2018. [Online]. Available: <a href="https://ec.europa.eu/info/law/law-topic/data-protection_en">https://ec.europa.eu/info/law/law-topic/data-protection_en</a> [Accessed Jan. 30, 2019]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ad06a8985f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/incentro/designing-and-building-an-event-tracking-backend-with-bigquery-1ad06a8985f9">Designing And Building An Event Tracking Backend with BigQuery</a> was originally published in <a href="https://medium.com/incentro">incentro</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>