<?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 Lrdev on Medium]]></title>
        <description><![CDATA[Stories by Lrdev on Medium]]></description>
        <link>https://medium.com/@lrdev?source=rss-ba4f38806830------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Lrdev on Medium</title>
            <link>https://medium.com/@lrdev?source=rss-ba4f38806830------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 16:18:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lrdev/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[Build a Pipeline for Harvesting Medium Top Author Data]]></title>
            <link>https://medium.com/data-science/build-a-pipeline-for-harvesting-medium-top-author-data-c4d7ed73729f?source=rss-ba4f38806830------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4d7ed73729f</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lrdev]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 01:14:44 GMT</pubDate>
            <atom:updated>2025-04-09T18:29:48.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Use Luigi and Docker to Build a Simple Data Engineering Pipeline for Medium</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3vLTc89opy2roulRkaiCPg.jpeg" /></figure><h3>Introduction</h3><p>The idea for this project started when some Python scripts I wrote for a data engineering pipeline got out of control:</p><ul><li>The pipeline required thousands of API calls to a REST service, each downloading a JSON file.</li><li>Some parts of the pipeline took a long time to run and the process would sometimes fail.</li></ul><p>My process looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*HLlcc3Y35b78lCEv8ilgQA.png" /></figure><p>These cumulative API calls added up:</p><ul><li>fetch parents (<em>1 request</em>)</li><li>for each parent fetch child (<em>150 requests</em>)</li><li>for each child fetch info (<em>5000 requests</em>)</li><li>for each info fetch configuration items (<em>14,000 requests…that’s a lot!)</em></li></ul><p>This was a quirk of the API I was using; there was no way to make bulk requests. There were many issues:</p><ul><li>The sequence took hours to run</li><li>If something failed, it was difficult to work out where to restart from</li><li>There was no way to check progress; if the scripts had been running for an hour, were they nearly done yet?</li></ul><p>Consulting Google, I found that my design was spookily similar to <a href="https://marcobonzanini.com/2015/10/24/building-data-pipelines-with-python-and-luigi/">this example</a> of how not to do things:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*U7nAeKpHUu5hkHnQQ7SrXg.png" /></figure><p>This thing had grown into a monster.</p><h3>Luigi To The Rescue</h3><p>I looked around for a lightweight data engineering framework which could support:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*W6DHlYRVdt6WcWGOCh315w.jpeg" /><figcaption>A famous plumber</figcaption></figure><ul><li>Workflow orchestration</li><li>Parallel processing</li><li>Simple deployment</li><li>A quick learning curve</li></ul><p>With those requirements in mind, <a href="https://github.com/spotify/luigi">Spotify Luigi</a> looked just right:</p><blockquote><em>Luigi is a Python module that helps you build complex pipelines of batch jobs. It handles dependency resolution, workflow management, visualization etc.</em></blockquote><p><a href="https://www.spotify.com/us/">Spotify</a> use Luigi for their data engineering batch jobs which recommend music, for example the Discover Weekly playlists (and I’m generally quite pleased with Discover Weekly’s choices for me, despite a recent disco epidemic).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*k9SgxdFB9ItDtRNArK42cw.jpeg" /><figcaption><em>My face when I saw Luigi do all the things</em></figcaption></figure><p>Luigi was surprisingly satisfying to work with, and I wondered how I could use it again outside of my day job. I thought of reusing the approach in a pipeline to harvest data about top Medium authors, and the text below describes a simple framework for a data engineering pipeline which could be reused in other domains.</p><p>This is geared towards <a href="https://www.oreilly.com/ideas/data-engineers-vs-data-scientists">data engineering vs data science</a>, although the modular architecture of Luigi should make the addition of analytics components straightforward. Put another way, this is a system design for extracting data, rather than an approach for analyzing and deriving insights from the data (maybe a topic for a future story).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSlg7a3-HCZM_YtHSNF3Qw.png" /><figcaption>Luigi gets to work on the pipes</figcaption></figure><h3>Harvesting Interesting Top Author Data from Medium</h3><p>Our pipeline will harvest data about the top authors in a publication:</p><ol><li>The list of authors this top story author follows</li><li>The total number of stories they’ve written</li><li>How many claps each story received</li><li>The average headline length of their stories</li><li>The average word count of their stories</li><li>Publications they’ve written for</li></ol><p>A quick note about the Medium API. The API itself is fairly limited. However, you can append ?format=json to many standard Medium URLs, which will return a JSON representation of the data usually shown on the page, along with some extra metadata. For example, <a href="https://towardsdatascience.com/">the front page of Towards Data Science</a> renders like this with the ?format=json parameter:</p><pre>])}while(1);&lt;/x&gt;{&quot;success&quot;:true,&quot;payload&quot;:{&quot;collection&quot;:{&quot;id&quot;:&quot;7f60cf5620c9&quot;,&quot;name&quot;:&quot;Towards Data Science&quot;,&quot;slug&quot;:&quot;towards-data-science&quot;,&quot;tags&quot;:[&quot;DATA SCIENCE&quot;,&quot;MACHINE LEARNING&quot;,&quot;ARTIFICIAL INTELLIGENCE&quot;,&quot;BIG DATA&quot;,&quot;ANALYTICS&quot;],&quot;creatorId&quot;:&quot;895063a310f4&quot;,&quot;description&quot;:&quot;Sharing concepts, ideas, and codes.&quot;,&quot;shortDescription&quot;:&quot;Sharing concepts, ideas, and codes.&quot;,&quot;image&quot;:{&quot;imageId&quot;:&quot;1*F0LADxTtsKOgmPa-_7iUEQ.jpeg&quot;,&quot;filter&quot;:&quot;&quot;,&quot;backgroundSize&quot;:&quot;&quot;,&quot;originalWidth&quot;:1275,&quot;originalHeight&quot;:1275,&quot;strategy&quot;:&quot;resample&quot;,&quot;height&quot;:0,&quot;width&quot;:0},&quot;metadata&quot;:{&quot;followerCount&quot;:171879,&quot;...etc</pre><p>Credit to <a href="https://medium.com/u/d540942266d0">Radu Raicea</a>’s excellent article <a href="https://medium.freecodecamp.org/how-i-used-python-to-find-interesting-people-on-medium-be9261b924b0">How I used Python to find interesting people to follow on Medium</a> for pointing me to this feature.</p><p>The JSON result needs a little bit of cleaning up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ac51de4f0b7c3b9b76b5767fd8c3e7a/href">https://medium.com/media/3ac51de4f0b7c3b9b76b5767fd8c3e7a/href</a></iframe><h3>Nuts and Bolts</h3><p>One key requirement was to make deployment of my Luigi workflow very simple. I wanted to assume only one thing about the deployment environment; that the Docker daemon would be available. With Docker, I wouldn’t need to be concerned with Python version mismatches or other environmental discrepancies.</p><p>It took me a little while to work out how to run Luigi inside Docker, though.</p><p>The first step is to start the central scheduler in it’s own container. You can do this with an existing image like <a href="https://github.com/axiom-data-science/docker-luigi">this one</a>.</p><p>You can submit jobs to the scheduler like this:</p><pre>PYTHONPATH=&#39;.&#39; luigi --module top_artists Top10Artists  --date-interval 2012-07</pre><p>That’s using an example from the Luigi docs.</p><p>So for deployment, this is the approach I took; a docker-compose file which includes:</p><ul><li>The Luigi central scheduler</li><li>A separate Python-based container for the Luigi tasks</li><li>An nginx container for exposing the reports</li></ul><p>The entry point of the tasks container sleeps for some period of time, then starts the Luigi pipeline, and this sleep takes the place of a cron job.</p><h4>Parallel Processing With Luigi</h4><p>My script was very slow, and I needed a way to run multiple URL fetching processes in parallel, which led to this design:</p><ul><li>A WrapperTask wraps all the components of the pipeline</li><li>The first URL fetch gets a list of many items which need to be queried individually (this is a single request)</li><li>These chunks are divided between workers, with the result of their work being placed into a file named after each worker id (e.g. 1.json)</li><li>From this point, the files are used by downstream workers</li></ul><p>The approach is adapted from <a href="http://engineering.pivotal.io/post/luigi-data-science/">this article</a>.</p><h4>Data Harvesting Tasks</h4><p>For the Medium data gathering pipeline, the WrapperTask looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79afe9ab34ee8171631f799dee9369ff/href">https://medium.com/media/79afe9ab34ee8171631f799dee9369ff/href</a></iframe><p>The requires() method is doing most of the work here, building up a list of the tasks which need to complete before PipelineTaskis considered complete.</p><p>The first task in the pipeline is FetchUserList. This gets a list of the Medium authors from the front page of a Medium publication. The list of authors is placed into a file which will be used by downstream tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f058106c61ef0a942388f3b6dd919ba/href">https://medium.com/media/7f058106c61ef0a942388f3b6dd919ba/href</a></iframe><p>Running it on the Towards Data Science publication will give us a list of authors mentioned on the page:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20e50fe790a90d7440cb0e08c5ea5b8e/href">https://medium.com/media/20e50fe790a90d7440cb0e08c5ea5b8e/href</a></iframe><p>You might notice that the list of authors returned in this result doesn’t match what’s displayed on the page; what’s up with that? It turns out that a page submits a series of requests to the Medium API when it loads up, and each returned JSON result includes a pointer to the next set of results in the series. We need to handle this paging behavior when obtaining the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78184c97ac0696eb61e6c682a7cd8950/href">https://medium.com/media/78184c97ac0696eb61e6c682a7cd8950/href</a></iframe><p>The implementation for this is largely borrowed from <a href="https://medium.com/u/d540942266d0">Radu Raicea</a>’s article.</p><p>Note that only one FetchUserList task will execute in a given pipeline, because we haven&#39;t included a file_number parameter.</p><p>The next task is FetchUserFollowings. This task will be executed concurrently by a number of workers, with parallelization being governed by the workers configuration parameter. When the task begins executing, it determines which section of the JSON file it is responsible for processing. The logic for determining the section is controlled by get_part_of_list():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b45178c36a134fe72d8446f743279d0/href">https://medium.com/media/6b45178c36a134fe72d8446f743279d0/href</a></iframe><p>The ExtractUserMetrics task picks out some interesting data points from the post data, for example the total clap count for each article:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48997e29763d7931b9cf67e09b63b52e/href">https://medium.com/media/48997e29763d7931b9cf67e09b63b52e/href</a></iframe><p>We can then derive a few averages from the extracted story data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21f8ea8d28e57ddf5551d4b34169c64d/href">https://medium.com/media/21f8ea8d28e57ddf5551d4b34169c64d/href</a></iframe><p>Finally, this line starts the process:</p><pre>luigi.build([PipelineTask()], workers=worker_count)</pre><h4>Exposing the Results</h4><p>You might want to expose the reports to end users, for example to data scientists on your team. One simple way is to add an nginx web server and list the contents of the output directory. This will allow anyone to hit a URL and download reports, with a report directory for each day.</p><h3>Trying It Out</h3><p>Ok, let’s kick the tires on this thing…</p><p>First of all, specify a starting point for the URL crawl, by specifying a collection_id in the luigi.conf file.</p><p>Once configured, there are a couple of ways to run the code:</p><ol><li>At development time, you can run __main__.py directly. You&#39;ll need to start Luigi first if you want to do this.</li><li>You can also run the whole application stack with docker-compose:</li></ol><pre>docker-compose up -d</pre><p>This will start Luigi, nginx and the tasks container, which will trigger __main__.py.</p><p>Inspecting the summary report, we can get some information about some of the top authors currently writing for Towards Data Science. For example, we can get some summary stats for one of the current top authors, <a href="https://medium.com/u/e2f299e30cb9">Will Koehrsen</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7292ae9db211cc0899ab4000b1049eca/href">https://medium.com/media/7292ae9db211cc0899ab4000b1049eca/href</a></iframe><p>Nice work, Will!</p><h3>Unit Testing</h3><p>I chose <a href="https://docs.pytest.org/en/latest/contents.html">pytest</a> as a testing framework. I like pytest for two main reasons:</p><ul><li>It requires less boilerplate code</li><li>You can use regular assert statements, instead of needing to remember a special syntax</li></ul><p>To test using a different configuration to the production version, you can use luigi.configuration.add_config_path() in your tests. This will load config from a specific location:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15dba9bc36eb4f9090c8e71c8de99c4d/href">https://medium.com/media/15dba9bc36eb4f9090c8e71c8de99c4d/href</a></iframe><p>I used the MockTarget class so I could run the tests in a repeatable way. I didn&#39;t want one test depending on data created by a previous test, or tests leaving behind result files after they finished running. MockTarget simulates a Luigi target which will store results in memory instead of writing them out to the file system.</p><p>Finally, to allow testing of URL requests without requiring the endpoint to be available, I used the <a href="https://pypi.org/project/requests-mock/">requests_mock</a> library.</p><p>The full source code for this sample pipeline is available on Github.</p><h3>Conclusions</h3><p>This project is a Luigi pipeline for harvesting top author data from Medium. The project started life as a simple framework for orchestrating a problematic data engineering process. The pipeline extracts information about authors and their stories by crawling URLs of a publication front page, then gathers some basic metrics about the top authors. It uses Luigi to coordinate the Python logic, and Docker to simplify deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4d7ed73729f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-a-pipeline-for-harvesting-medium-top-author-data-c4d7ed73729f">Build a Pipeline for Harvesting Medium Top Author Data</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[A blockchain experiment with Apache Kafka]]></title>
            <link>https://medium.com/free-code-camp/a-blockchain-experiment-with-apache-kafka-97ee0ab6aefc?source=rss-ba4f38806830------2</link>
            <guid isPermaLink="false">https://medium.com/p/97ee0ab6aefc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lrdev]]></dc:creator>
            <pubDate>Thu, 21 Dec 2017 22:19:23 GMT</pubDate>
            <atom:updated>2025-04-09T18:32:14.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqtvMnrUm7kL3xSHSWUqRg.jpeg" /></figure><p>Blockchain technology and Apache Kafka share characteristics which suggest a natural affinity. For instance, both share the concept of an ‘immutable append only log’. In the case of a Kafka partition:</p><blockquote><em>Each partition is an ordered, immutable sequence of records that is continually appended to — a structured commit log. The records in the partitions are each assigned a sequential id number called the offset that uniquely identifies each record within the partition [</em><a href="https://kafka.apache.org/intro"><em>Apache Kafka</em></a><em>]</em></blockquote><p>Whereas a blockchain can be described as:</p><blockquote><em>a continuously growing list of records, called blocks, which are linked and secured using cryptography. Each block typically contains a hash pointer as a link to a previous block, a timestamp and transaction data [</em><a href="https://en.wikipedia.org/wiki/Blockchain"><em>Wikipedia</em></a><em>]</em></blockquote><p>Clearly, these technologies share the parallel concepts of an immutable sequential structure, with Kafka being particularly optimized for high throughput and horizontal scalability, and blockchain excelling in guaranteeing the order and structure of a sequence.</p><p>By integrating these technologies, we can create a platform for experimenting with blockchain concepts.</p><p>Kafka provides a convenient framework for distributed peer to peer communication, with some characteristics particularly suitable for blockchain applications. While this approach may not be viable in a trustless public environment, there could be practical uses in a private or consortium network. See <a href="https://blog.gridplus.io/scaling-blockchains-with-apache-kafka-814c85781c6">Scaling Blockchains with Apache Kafka</a> for further ideas on how this could be implemented.</p><p>Additionally, with some experimentation, we may be able to draw on concepts already implemented in Kafka (e.g. sharding by partition) to explore solutions to blockchain challenges in public networks (e.g. scalability problems).</p><p>The purpose of this experiment is therefore to take a simple blockchain implementation and port it to the Kafka platform; we’ll take Kafka’s concept of a sequential log and guarantee immutability by chaining the entries together with hashes. The blockchain topic on Kafka will become our distributed ledger. Graphically, it will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FIHzWNevFvDt0Yj4hL-Bnw.png" /><figcaption>Visual of a Kafka blockchain</figcaption></figure><h3>Introduction to Kafka</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*1oiiOWXlKaD_SSuElTaNGA.png" /></figure><p>Kafka is a streaming platform designed for high-throughput, real-time messaging, i.e. it enables publication and subscription to streams of records. In this respect it is similar to a message queue or a traditional enterprise messaging system. Some of the characteristics are:</p><ul><li>High throughput: Kafka brokers can absorb gigabytes of data per second, translating into millions of messages per second. You can read more about the scalability characteristics in <a href="https://engineering.linkedin.com/kafka/benchmarking-apache-kafka-2-million-writes-second-three-cheap-machines">Benchmarking Apache Kafka: 2 Million Writes Per Second</a>.</li><li>Competing consumers: Simultaneous delivery of messages to multiple consumers, typically expensive in traditional messaging systems, is no more complex than for a single consumer. This means we can design for <a href="http://www.enterpriseintegrationpatterns.com/patterns/messaging/CompetingConsumers.html">competing consumers</a>, guaranteeing that each consumer will receive only one of the messages and achieving a high degree of horizontal scalability.</li><li>Fault tolerance: By replicating data across multiple nodes in a cluster, the impact of individual node failures is minimized.</li><li>Message retention and replay: Kafka brokers maintain a record of consumer offsets — a consumer’s position in the stream of messages. Using this, consumers can rewind to a previous position in the stream even if the messages have already been delivered, allowing them to recreate the status of the system at a point in time. Brokers can be configured to retain messages indefinitely, which is necessary for blockchain applications.</li></ul><p>In Kafka, each topic is split into partitions, where each partition is a sequence of records which is continually appended to. This is similar to a text log file, where new lines are appended to the end. The entries in the partition are each assigned a sequential id, called an offset, which uniquely identifies the record.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDcZFdrpk1TqMd9g50VU3g.png" /><figcaption>Kafka partitioning</figcaption></figure><p>The Kafka broker can be queried by offset, i.e. a consumer can reset its offset to some arbitrary point in the log to retrieve records from that point forward.</p><h3>Tutorial</h3><p>Full source code is available <a href="https://github.com/pixelwrench/kafka-blockchain">here</a>.</p><h4><strong>Prerequisites</strong></h4><ul><li>Some understanding of blockchain concepts: The tutorial below is based on implementations from <a href="https://hackernoon.com/learn-blockchains-by-building-one-117428612f46">Daniel van Flymen</a> and <a href="https://medium.com/crypto-currently/lets-build-the-tiniest-blockchain-e70965a248b">Gerald Nash</a>, both excellent practical introductions. The following tutorial builds heavily on these concepts, while using Kafka as the message transport. In effect, we’ll port a Python blockchain to Kafka, while maintaining most of the current implementation.</li><li>Basic knowledge of Python: the code is written for Python 3.6.</li><li><a href="https://www.docker.com/">Docker</a>: docker-compose is used to run the Kafka broker.</li><li><a href="https://github.com/edenhill/kafkacat">kafkacat</a>: This is a useful tool for interacting with Kafka (e.g. publishing messages to topics)</li></ul><p>On startup, our Kafka consumer will try to do three things: initialize a new blockchain if one has not yet been created; build an internal representation of the current state of the blockchain topic; then begin reading transactions in a loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77f5e81431bde1386143e85120f6692d/href">https://medium.com/media/77f5e81431bde1386143e85120f6692d/href</a></iframe><p>The initialization step looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09502d9e09e71e5f165e94bc2e5ddde2/href">https://medium.com/media/09502d9e09e71e5f165e94bc2e5ddde2/href</a></iframe><p>First, we find the highest available offset on the blockchain topic. If nothing has ever been published to the topic, the blockchain is new, so we start by creating and publishing the genesis block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1acaa4fbc03f380cdaee5093b918e29d/href">https://medium.com/media/1acaa4fbc03f380cdaee5093b918e29d/href</a></iframe><p>In read_and_validate_chain(), we’ll first create a consumer to read from the blockchain topic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfe2afc8812f507be1dbbb7a41ffb4e2/href">https://medium.com/media/bfe2afc8812f507be1dbbb7a41ffb4e2/href</a></iframe><p>Some notes on the parameters we’re creating this consumer with:</p><ul><li>Setting the consumer group to the blockchain group allows the broker to keep a reference of the offset the consumers have reached, for a given partition and topic</li><li>auto_offset_reset=OffsetType.EARLIEST indicates that we’ll begin downloading messages from the start of the topic.</li><li>auto_commit_enable=True periodically notifies the broker of the offset we’ve just consumed (as opposed to manually committing)</li><li>reset_offset_on_start=True is a switch which activates the auto_offset_reset for the consumer</li><li>consumer_timeout_ms=5000 will trigger the consumer to return from the method after five seconds if no new messages are being read (we’ve reached the end of the chain)</li></ul><p>Then we begin reading block messages from the blockchain topic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec915049ada62cc0d7b852885723995a/href">https://medium.com/media/ec915049ada62cc0d7b852885723995a/href</a></iframe><p>For each message we receive:</p><ol><li>If it’s the first block in the chain, skip validation and add to our internal copy (this is the genesis block)</li><li>Otherwise, check the block is valid with respect to the previous block, and append it to our copy</li><li>Keep a note of the offset of the block we just consumed</li></ol><p>At the end of this process, we’ll have downloaded the whole chain, discarding any invalid blocks, and we’ll have a reference to the offset of the latest block.</p><p>At this point, we’re ready to create a consumer on the transactions topic:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e21d48800889b31084964082fd3f40a2/href">https://medium.com/media/e21d48800889b31084964082fd3f40a2/href</a></iframe><p>Our example topic has been created with two partitions, to demonstrate how partitioning works in Kafka. The partitions are set up in the docker-compose.yml file, with this line:</p><p>KAFKA_CREATE_TOPICS=transactions:2:1,blockchain:1:1</p><p>transactions:2:1 specifies the number of partitions and the replication factor (i.e. how many brokers will maintain a copy of the data on this partition).</p><p>This time, our consumer will start from OffsetType.LATEST so we only get transactions published from the current time onwards.</p><p>By pinning the consumer to a specific partition of the transactions topic, we can increase the total throughput of all consumers on the topic. The Kafka broker will evenly distribute incoming messages across the two partitions of the transactions topic, unless we specify a partition when we publish to the topic. This means each consumer will be responsible for processing 50% of the messages, doubling the potential throughput of a single consumer.</p><p>Now we can begin consuming transactions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bc4871b84bafa5f80f75dde060a8bf7/href">https://medium.com/media/3bc4871b84bafa5f80f75dde060a8bf7/href</a></iframe><p>As transactions are received, we’ll add them to an internal list. Every three transactions, we’ll create a new block and call mine():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24f29b7724efdc89fe1a118a650539c4/href">https://medium.com/media/24f29b7724efdc89fe1a118a650539c4/href</a></iframe><ol><li>First, we’ll check if our blockchain is the longest one in the network; is our saved offset the latest, or have other nodes already published later blocks to the blockchain? This is our consensus step.</li><li>If new blocks have already been appended, we’ll make use of the read_and_validate_chain from before, this time supplying our latest known offset to retrieve only the newer blocks.</li><li>At this point, we can attempt to calculate the proof of work, basing it on the proof from the latest block.</li><li>To reward ourselves for solving the proof of work, we can insert a transaction into the block, paying ourselves a small block reward.</li><li>Finally, we’ll publish our block onto the blockchain topic. The publish method looks like this:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/667208c757b3f35a6636e30da282639b/href">https://medium.com/media/667208c757b3f35a6636e30da282639b/href</a></iframe><h3>In Action</h3><ol><li>First start the broker:</li></ol><p>docker-compose up -d</p><p>2. Run a consumer on partition 0:</p><p>python kafka_blockchain.py 0</p><p>3. Publish 3 transactions directly to partition 0:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f22e8c92e90fc9c5123be8486e8d4676/href">https://medium.com/media/f22e8c92e90fc9c5123be8486e8d4676/href</a></iframe><p>4. Check the transactions were added to a block on the blockchain topic:</p><p>kafkacat -C -b kafka:9092 -t blockchain</p><p>You should see output like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2ca04d9a1e2ac33d5e37bf89e863605/href">https://medium.com/media/e2ca04d9a1e2ac33d5e37bf89e863605/href</a></iframe><p>To balance transactions across two consumers, start a second consumer on partition 1, and remove -p 0 from the publication script above.</p><h3>Conclusion</h3><p>Kafka can provide the foundation for a simple framework for blockchain experimentation. We can take advantage of features built into the platform, and associated tools like kafkacat, to experiment with distributed peer to peer transactions.</p><p>While scaling transactions in a public setting presents one set of issues, within a private network or consortium, where real-world trust is already established, transaction scaling might be achieved via an implementation which takes advantage of Kafka concepts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97ee0ab6aefc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/a-blockchain-experiment-with-apache-kafka-97ee0ab6aefc">A blockchain experiment with Apache Kafka</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>