<?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 Lam Chan on Medium]]></title>
        <description><![CDATA[Stories by Lam Chan on Medium]]></description>
        <link>https://medium.com/@lam.chan?source=rss-f89d46748c74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jehnCjtD6d4Bbuov0t0qtQ@2x.jpeg</url>
            <title>Stories by Lam Chan on Medium</title>
            <link>https://medium.com/@lam.chan?source=rss-f89d46748c74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 21:40:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lam.chan/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[Streams for Everyone]]></title>
            <link>https://medium.com/@lam.chan/streams-for-everyone-92d50108ed72?source=rss-f89d46748c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/92d50108ed72</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Lam Chan]]></dc:creator>
            <pubDate>Thu, 09 Mar 2017 02:05:54 GMT</pubDate>
            <atom:updated>2017-03-20T18:16:29.646Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week, I had an idea of creating a supplemental <a href="https://github.com/xogroup/bunnybus-cli">CLI</a> interface for us to leverage RabbitMQ and <a href="https://github.com/xogroup/bunnybus">BunnyBus</a> without needing to bootstrap an application. My original thought was a quick NodeJs project to profit on some pipe() chaining. It was not until I ventured into the guts of the situation that I realized the NodeJs <strong>Stream</strong> is an unwieldily beast needing to be tamed with proper documentation and diagrams.</p><h3><strong>What is a Stream?</strong></h3><p>Quoted from <a href="https://en.wikipedia.org/wiki/Stream_(computing)">Wikipedia</a></p><blockquote>a stream is a sequence of data elements made available over time</blockquote><p>A stream provides an efficient way of handling a big set of data. Streams are important concepts in most classical languages. We tend to use streams when the size of the data is unknown or varying. The reason is anytime data is handled as a whole in an application, it has to be loaded into memory. So if you have a piece of data that is overly large, it can cause unwanted memory pressure and out of memory exceptions. Streams allow you to handle only what is at hand.</p><p>Let’s imagine we have a web server handling HTTP request without streams. We want to write all of these request to the file system. Since we are not using streams, we would load all of the data from the request into memory, and then write that entire body of data into the file system. This would require we have enough memory to accommodate the entire request. This will cause undulation with our memory profile because it is necessary to allocate memory for the request. Then afterwards, we would need to clean up the memory space once we are done.</p><p>Now, using streams, we would get a stream handler (object pointer) passed to us from our socket listener or web middleware. With a handle on the stream, we can redirect the output to the file system. The memory footprint for the stream would only be as big as the largest segment of data in transit at that point in time. So instead of needing 1 MB of memory to handle the whole request, you might only need 8 KB or as large as your stream buffer will allow.</p><h3><strong>What are NodeJs Streams?</strong></h3><p>Streams in NodeJs embodies the core concepts from above. There are 3 main components essential for handling streams.</p><ul><li>Readable — Producer of stream data.</li><li>Writable — Consumer of stream data.</li><li>Transform — Used when manipulation of the stream data needs to occur.</li></ul><p>We would normally connect the components in this way.</p><p>Readable ➙ Transform ➙ Writable</p><p>Interestedly, streams in NodeJs has allowance for multiple data types. Classical streams normally has strict adherence for providing transport of only byte arrays. But in NodeJs, we can also specify UTF8 strings and objects. Yes, you heard me right, objects!</p><p>The flexibility around various type handling is useful. We can build an input pipe that consumes raw byte data which is the usual format for things serialized with binary formatting. Then attach transforms to the pipeline to allow us to convert the raw bytes to string types. Which then can allow us to interpret further and transform those strings to objects. This basically allow us to break down the work of transformation or stream processing over several transforms which is great for dividing the concentration of work.</p><p>An example of this can be represented when we need to read data in from a file stream. Followed by conversion of that stream data to valid UTF8 strings. And then interpreting the strings into JSON blobs. Where each of those JSON blob would be deserialized into an object. And finally, written into Elasticsearch as a destination source. Once again, streams allow us to only process what is necessary in order to interpret for the next step.</p><p>A side note, the NodeJs stream interface has <a href="https://nodejs.org/en/blog/feature/streams2/">evolved</a> from where it first started. So you have to put in special care when looking at documentation and module interfaces to understand the full picture.</p><h3><strong>Disconnects With NodeJs Stream Documentation</strong></h3><p>I’m coining this statement for a future meme.</p><blockquote>Everyone uses streams, but no one writes the sinks for them</blockquote><p>As I was going through Google finding reputable examples and write-ups for how to manage states of a stream, I found an abundant coverage on how to use them. But in the area of how to create stream components for Readable, Writable, Transform and Duplex, it was close to none existent. Here are the handful of useful resources which helped me.</p><ul><li><a href="https://github.com/substack/stream-handbook">Stream Handbook</a></li><li><a href="https://github.com/jessicaquynh/nodejs.org/blob/e646720b5633de37d397ddc5c660d3e1bff1f39c/locale/en/docs/guides/backpressuring-in-streams.md#lifecycle-of-pipe">Backpressuring in Streams</a></li><li><a href="https://www.sandersdenardi.com/readable-writable-transform-streams-node/">Readable, Writable and Transform Streams in Node.js</a></li><li><a href="https://nodejs.org/api/stream.html">NodeJs Stream API Guide</a></li></ul><p>From all of the web post I found, they mostly parroted the <em>NodeJs Stream API Guide</em>. It would not be a problem if the NodeJs documentation is accurate, but there are more than a few disconnects between the definition for the end caller and the definition for component implementations.</p><p>An example of when does <a href="https://nodejs.org/api/stream.html#stream_writable_end_chunk_encoding_callback">end</a>() get invoked for a Writable component. It is obvious to me that it is called and should be invoked within the pipe() chain when the Readable component has no more data. But for the implementation <a href="https://nodejs.org/api/stream.html#stream_implementing_a_writable_stream">example</a>, there is zero coverage of this consumer interface. This really left me hanging as to how a Writable component detects the end of stream so that we can clean up underlying system resource and not hang the application.</p><p>Another example is the confusion around each event emitted by the components. Let’s take Writable as an example again and drive into the <a href="https://nodejs.org/api/stream.html#stream_event_close">close</a> event. The document states this event is emitted when the underlying resource is done cleaning up. But does this mean you as the implementor of the component and the consumer of said resource are to emit the event manually. Or is there an underlying function to call which will take care of the eventing? Once again, the implementation <a href="https://nodejs.org/api/stream.html#stream_implementing_a_writable_stream">example</a> has this missing.</p><p>All good API specifications have a few things in common. The one most relevant is <strong>expected and predictable behavior</strong> in design. When implementing stream components, the interaction with stream events (data, close, drain, end, finish and etc…) are unclear for which ones are emitted by the underlying super class or in need of self invocation through emit(). I want to impress upon you, our future API providers; Please do not fall into similar design flaws. It is a horrible experience for developers implementing against any spec.</p><h3><strong>Finding How The Spice (Stream) Flows</strong></h3><p>When I am befuddled, I look towards building experiments to help untangle the web of information. Here is one such example allowing me to test the eventing from the pipe().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b5677face9e137d0fc78dcf4702b8f8/href">https://medium.com/media/5b5677face9e137d0fc78dcf4702b8f8/href</a></iframe><p>This experiment allowed me to see the drip of events down stream from one component to another while using pipe(). It allowed me to connect the cause and effect. Here are a few questions I was able to answer.</p><ul><li>When does the _read() get called once the pipe is connected?</li><li>When is _write() triggered when data is pumped from a Readable?</li><li>Is the drain event managed by the Writable interface or something I need to emit()?</li><li>Can I manipulate the drain event through control of highWaterMark?</li><li>Are the finished and close events managed by the Writable interface?</li><li>Does end() method within the Writable get called?</li><li>Is there a corresponding private _end() function to implement for the consumer facing end()?</li><li>How much data is needed to force _writev() to be called?</li><li>Is resume()/pause() for Readable self managed.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0e3a8daa7e5252c4f9ae47f3156472d/href">https://medium.com/media/b0e3a8daa7e5252c4f9ae47f3156472d/href</a></iframe><p>It took me several different experimental setups to answer what I needed. But I urge you to try this to verify behaviors. This is a great outlet for bypassing unfinished documentation or can be used to verify the documentation itself is correct.</p><h3><strong>How It Flows</strong></h3><p>I was inspired to create a diagram based on the ASCII art I saw from one of the back pressure article. I added details where lacking and also tried to make event causation more clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Xv-enWqwdy_AlMYYl4JVg.png" /></figure><p>It is important to note pipe contains no magic and only operates within normal means when both the Readable and Writable interfaces are triggered in a timely fashion. For example, if the _read() method is called, but the corresponding this.push() is not invoked, then the piping mechanism will just hang. This is also true with the _write() method and the associated callback() needing to be reconciled.</p><p>There are events such as finish and close which are not emitted within the Readable and Writable super class. These events are optional for you to emit yourself. I’ve had to use them while closing underlying resources like sockets or other file descriptors. It is very useful to leverage these while unit testing to get a truth on when either end of the pipe is truly no longer able to act.</p><p>The _write() invocations are never guaranteed any data when they are called. Expect none by default. When the pipe() starts up, and calls on _read(), the underlying data source for the Readable may not be initialized yet. This problem exist because some data source may require instantiation of database connections while _read() is invoked. So for some implementation to support delayed initialization, it is necessary to either pass empty data or keep a semaphore to count how many _read() calls has been made so equivalent quantity of this.push() can be invoked.</p><p>The end() interface in Writable is an optional implementation. There is no private method to implement for this so you would just override the public interface if needed. The call made to end() is never guaranteed to be the last call within the stream of events. <a href="http://stackoverflow.com/questions/28367144/stream-writable-end-called-before-write-callback">Others</a> and I have seen this execute out of order.</p><p>All Writable components which includes Transform and Duplex utilize the highWaterMark option to throttle the Readable component. This is a built in feature and does not need to be manipulate. It is easy to trigger the behavior of throttling when you set the highWaterMark to be of smaller value than the size of data being passed. You should also be able to trigger throttling behavior by returning false within the _write interface.</p><h3>About the Author</h3><h4>Lam Chan</h4><p>Lam is a Software Architect for the Locals Squads @ XO Group. He is a seasoned polyglot engineer with over 16 years of professional <br>experience working with startups and multiple fortune 500 companies. When he is away from the office, he enjoys contributing to OSS <br>projects and dabbles with wood working projects. Find out more about Lam on <a href="https://www.linkedin.com/in/lamchan">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92d50108ed72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency in Three Flavors]]></title>
            <link>https://medium.com/@lam.chan/concurrency-in-three-flavors-51ed709876fb?source=rss-f89d46748c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ed709876fb</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Lam Chan]]></dc:creator>
            <pubDate>Wed, 22 Feb 2017 22:45:58 GMT</pubDate>
            <atom:updated>2017-03-01T04:13:27.552Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working with Golang this past week and it really got me thinking about how different languages manage control flows when combining concurrency with asynchronous typed task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*ZiSObkwhgSe7NyXipQ1W-A.jpeg" /></figure><h3>Concurrency</h3><p>Definition from <a href="https://en.wikipedia.org/wiki/Concurrency_(computer_science)">Wikipedia</a></p><blockquote>concurrency is the decomposability property of a program, algorithm, or problem into order-independent or partially-ordered components or units</blockquote><p>We tend to use concurrency to help solve many problems in software especially when the problem is big. We leverage concurrency to break down a big problem into many smaller problem which we piece back together. This process is called map-reduce. The benefit is revealed when all of these smaller problems can be solved at the same time.</p><p>An example of this can be seen in Elasticsearch and the sharding techniques for the search indices. When there is a big index, this body can be broken apart as shards across a cluster of nodes. Now each node only has the responsibility to lookup search request for what it holds. When a search request comes in, every node takes part in the lookup at the same time. When all results return from each node, a reduction process takes place to stitch the list back to the caller.</p><h3>Concurrency and Back Pressure</h3><p>When building for concurrency, it is important to understand processing velocity in order to handle back pressure. Processing velocity is the speed at which a system can handle request. When designing a middle man component for a data pipe such as a stream processor, awareness is necessary around how fast requests are made versus how fast the downstream systems can take the results. In the event of back pressure, strategies need to be created to handle the imbalance. Strategies may include buffering, signals for back off to upstream clients, or internal rate limit cap.</p><h3>The Problem and Solution</h3><p>The problem I worked on involved correcting for a bug in S3. When you upload objects using pre-signed urls, and ACL is not declared as part of the PUT request. The final object that is stored in S3 is not assigned an owner. This object ends up in an orphaned state that can not be operated on. The only way to repair it is to copy the object out, delete the original and PUT it back in with the corrected ACL.</p><p>We have around several million objects in a single bucket with objects of variable size. Ideal processing of this would be anything under a day of compute.</p><p>This was when I chose to try Golang having heard of great I/O and low compute overhead. I ended up picking up Golang within a day and engineered a throw away application in another day. The application achieved the repair of our S3 bucket in 40 minutes of time and was processing at a good clip of 256 MB/sec. What amazed me was how easy it was to write a fully concurrent application in a new language operating at this performance level.</p><h3>Golang Channels</h3><p>Two things define concurrency in Golang. <strong>Goroutines</strong> and <strong>channels</strong>, are incredible when used correctly in combination. Goroutines are decorators you can use around a function to execute it in the context of a separate *light* thread. An example of this being useful is when you need to spawn a dispatcher to create background workers to listen to a queue. With all threads that are created, there is going to be a time when you need the context to be coalesced back together. This is when channels come into play. Golang has a lot of language features built around channels as a first class citizens. The for loop is a good example of this where you can setup a loop to wait on items to come off a channel indefinitely.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/407502eb37b6ed526bbc3d8316649650/href">https://medium.com/media/407502eb37b6ed526bbc3d8316649650/href</a></iframe><p>This example above represents a job dispatcher and it highlights a for loop with a select expression. The for loop runs indefinitely and is conditionally held together by the select statement which dequeues job off the Job queue. When that happens, an IIFE is created and executed as a goroutine. Once the IIFE starts running, a worker is dequeued to process the job. When finished, the worker is enqueued back into the worker pool.</p><p>Let’s take focus on make(chan Job) and mak(chan Worker, 40). These expressions are invoking the creation of two channels for the job and worker pool. They are different because the channel for jobs do not have a upper limit in how many items it can hold. But the channel for the worker pool does have a capacity of 40 which helps us rate limit how fast we can process which is at the processing limit (CPU/Cores) of the system we are running on. When a job is dispatched, the goroutine is limited by the amount of workers that are available so this limits how many jobs we can process in parallel.</p><p>As the worker processes the job, the results from the job can be sent back on another channel to another component handling the merging (reduction) of the results to the caller or sent further down stream.</p><h3>NodeJs Event Loop</h3><p>Concurrency in NodeJs is a sticky subject because the user space your application runs in is a single threaded context. This user space is also known as the event loop which is akin to co-routines or co-threading. The participants (your code) of this event loop requires that all actors (functions) be good citizens and share the resource evenly to prevent blockages. When the aforementioned is implemented, the event loop is very fast because there is no threading and hence no context switching at the lower level. This methodology is akin to how a few low level TCP interfaces (Akka) are written.</p><p>NodeJs treats asynchronous concurrency as a first class citizen. Users can pick from several styles of available control flow. Here, we will talk about two.</p><h4>Async</h4><p>Native Node.js callback style was the first built in control flow to handle asynchronous concurrency. Basically when the task is done, a callback function is invoked to reconcile back to the caller the result(s) or error(s).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17611b847b2466fdfdab6adcd2f5cb5a/href">https://medium.com/media/17611b847b2466fdfdab6adcd2f5cb5a/href</a></iframe><p>The listJobs() method returns a bunch jobs. Using the asynclib callback control flow library, we use it to help us map the collection of jobs into a process that does asynchronous processing (does not require resource from the event loop). The Async.mapLimit() takes in a number for how many of these jobs to execute concurrently. This is similar to the Golang example with how many workers are active at once.</p><h4>Promises</h4><p>Promises were added as a follow up support in Node.js to modify the control flow for asynchronous programming resemble more like synchronous styles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ec89fbf4f88cc392c2d80a57fbc85a0/href">https://medium.com/media/3ec89fbf4f88cc392c2d80a57fbc85a0/href</a></iframe><p>The concerning difference in this example is the control flow framework used where we replaced previous Async with Promise. The map() method still takes in a max concurrency number to handle how many task we can at most process at one time.</p><h3>.Net TPL</h3><p>The advent of LINQ, gave C# an easy way to handle collection and enabled lazy evaluation. A good side effect of LINQ that was not effectively promoted are the <strong>RX</strong> (<a href="https://github.com/Reactive-Extensions/Rx.NET">Reactive Extensions</a>) and <strong>TPL</strong> (<a href="https://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx">Task Parallel Library</a>) frameworks. I used TPL extensively to maximize concurrency for batch processing. The reason is that TPL leverages the concept of building blocks to allow for composability in a data processing chain. There are a myriad of built in data block control flows like ActionBlock, TransformBlock and JoinBlock to name a few.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/138a70f5923b7699b76e14596519fc90/href">https://medium.com/media/138a70f5923b7699b76e14596519fc90/href</a></iframe><p>This example is some what similar to the Node.js Promises and Golang example above. In TPL, we create these building blocks which perform our actions, but are linked together by self managed in memory queues. In Golang, we created channels to represent this. The concurrency restriction is declared as part of the block instantiation using MaxDegreeOfParallelism flag. The processBlock handles the job processing and the aggregationBlock handles the reduction. This aspect of having to feed in the jobs to the starting block is some what similar to Golang’s tying a channel to the dispatcher and feeding jobs into the channel.</p><h3>Conclusion</h3><p>I found the reflection of different control flow mechanism interesting in how close each framework/language resemble at times, but also how far these concepts diverged in style. In the end, it is about understanding the tools available to you and picking the right one for the job at hand.</p><h3>About the Author</h3><h4>Lam Chan</h4><p>Lam is a Software Architect for the Locals Squads @ XO Group. He is a seasoned polyglot engineer with over 16 years of professional <br>experience working with startups and multiple fortune 500 companies. When he is away from the office, he enjoys contributing to OSS <br>projects and dabbles with wood working projects. Find out more about Lam on <a href="https://www.linkedin.com/in/lamchan">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ed709876fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BunnyBus : Building a Data Transit System]]></title>
            <link>https://medium.com/@lam.chan/bunnybus-building-a-data-transit-system-b9647f6283e5?source=rss-f89d46748c74------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9647f6283e5</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[enterprise-bus]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Lam Chan]]></dc:creator>
            <pubDate>Mon, 13 Feb 2017 16:03:44 GMT</pubDate>
            <atom:updated>2017-02-13T17:02:43.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introductions</h3><p>I’ve had the pleasure of working at a few enterprise sized companies where data was treated as first class citizen. This is also true here at XO Group, where life of the data begins when the bride and groom register. This is followed by various steps of validation, transformation and data intelligence processing. Which eventually lands in the hands of our vendor(s) to capture leads or to help other couples find services based on similar matches.</p><p>I work in the Local’s team where I helped design a large portion of the data piping architecture. When I first joined the team, we used NServiceBus (NSB) in .NET to move messages around. Anyone having used NSB can appreciate the relative ease of creating an enterprise bus facade over MSMQ. As the years passed, our group needed to keep up with technology to make ourselves competitive both within XO and current technology culture. We finalized on Node.js and <a href="https://www.hapijs.com/">hapijs</a> for all the benefits a single threaded event loop and a vibrant open source community would bring.</p><h3>What is an enterprise data bus?</h3><p>Quote from <a href="https://en.wikipedia.org/wiki/Enterprise_service_bus">wikipedia</a>.</p><blockquote>An enterprise service bus (ESB) is implementing a communication system between mutually interacting software applications in a service-oriented architecture</blockquote><p>The following are basic requirements for an ESB:</p><ul><li>Route message from publisher to any subscriber.</li><li>Handle rejected messages.</li><li>Persist data when subscribers have gone offline.</li><li>Be fault tolerant.</li><li>Provide for retry of data handling.</li><li>Buffer I/O differentials between publisher and consumer.</li></ul><h3>Why is an enterprise data bus important?</h3><p>We manage a <em>microservice</em> architecture which is a highly specialized form of SOA. Within this environment, we rely on queues to relay data from one application domain to another for requests that should be performed asynchronously. As a side note, we maintain homogenous data contracts for each queue. This can lead to an extraordinary amount of combinations for queues and routes needing to be created and maintained. In addition, these combinations are always in flux since services are brought in and out of play frequently.</p><p>For all the scenario above, overlaying an ESB facade just made sense.</p><h4>Choosing RabbitMQ</h4><p>As we first started porting our .Net stack over, XO Tech primarily used AWS SNS and SQS to bus data between teams (application domains). While this worked well for small amount of applications, the management of infrastructure did not scale well for Local’s application set where a single application domain had as many as 20 different events to publish with.</p><p>I started investigating different queue technology that would work with Node.js. I eventually landed upon RabbitMQ for the following reasons:</p><ul><li>Raw performance.</li><li>FIFO (first in first out)</li><li>Dynamic and flexible routing with route keys.</li><li>Durable and fault tolerant.</li><li>Built in realtime GUI for monitoring and debugging.</li></ul><h4>Using RabbitMQ</h4><p>With any queue or data storage solutions, you have to work with low level drivers to get data in and out. Mostly, we aimed to find a driver that gave us the right abstractions away from the device and the right amount of feature. In, .Net, NSB afforded us the correct level of abstraction. In Node.js, using RabbitMQ equated to using the amqplib driver. This meant each of our applications would still need to manage connections, channels, exchanges and queues manually. This was when we decided to write our own Node.js module to gain the abstraction of NSB like capabilities.</p><h4>BunnyBus</h4><p>The original incarnation of BunnyBus came as flash of brilliance while discovering the power of Javascript. Hard work was placed on solidifying our <em>microservice</em> platform and the outcome is a module responsible for relaying all of our asynchronous traffic within Local’s ecosystem.</p><p>Much of our work would not have been possible without the huge amount of resources available in the open source community. In return, we want to share ‘BunnyBus`, our ESB facading module utilizing RabbitMQ.</p><p><strong>Goals of BunnyBus</strong></p><ul><li>Make it easy to bootstrap an enterprise bus to applications.</li><li>Maintain high performance when compared to using amqplib directly.</li><li>Facilitate flexibility in event subscription management.</li><li>Create a developer-centric API.</li><li>Support both Node.js callbacks and A+/Promise specifications.</li><li>Automate <a href="http://rubybunny.info/articles/exchanges.html">exchange</a> creation for publishing.</li><li>Automate queue creation for both subscriptions and error handling for subscriptions.</li><li>Automate connection and channel recovery when things become corrupt.</li><li>Easily extend state management for the process manager.</li><li>Allow extensions for listing event subscriptions.</li><li>Create extensions for stopping subscriptions from being active with a simple call.</li><li>Complete test coverage.</li><li>Fully documented</li><li>ES6 compliant.</li></ul><p><strong>How to get started</strong></p><p>Simple, just npm i bunnybus</p><p><strong>Definition of what a route is</strong></p><p>A route is defined by a route key or event. A route key is something akin to a addressing system. A publisher has to provide one such as systemA.user-create. Any number of subscriber can opt to listen to the route key to get the message delivered to them. Subscribers can even ask BunnyBus to listen to all route keys like this systemA.* and all messages that are published with a matching value will be received.</p><p><strong>What does a subscriber look like</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62e6a8ebe328e0358e855979fb0d14da/href">https://medium.com/media/62e6a8ebe328e0358e855979fb0d14da/href</a></iframe><p>So the code is pretty simple, configure a handler object that has a key which represents the name of event or route key. The value for this key is a function with the signature of message (content that was sent on the bus) and ack() (a function you use to clear the message off the bus). Lastly, using bunnyBus, subscribe() is what creates `queue1` and sets up the routing for messages to be delivered to this queue.</p><p>You can configure multiple route keys and handlers in the handler object so a queue handler for many different events. In addition, BunnyBus supports polymorphic payloads for types of String, Object and Buffer for the same event.</p><p><strong>What does a publisher look like</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a12da5a86ee9d08d3bf0f439e3461a/href">https://medium.com/media/18a12da5a86ee9d08d3bf0f439e3461a/href</a></iframe><p>Here, we created a payload with properties of event (containing route key) and body (just some data to send). Then we send it with publish(). Notice no queue is specified. But rest assured the message will be routed to the subscriber example above based on the event (route key) in the message.</p><p><strong>There is More!</strong></p><p>BunnyBus has a lot of power when wielded properly. Check out our <a href="https://github.com/xogroup/bunnybus/blob/master/API.md">documentation</a> located within our <a href="https://github.com/xogroup/bunnybus">Github repo.</a></p><p><strong>How do we use it?</strong></p><p>We combine the power of BunnyBus with flexibility of hapijs to build some awesome plugins that can be attached to any process allowing ESB capabilities to all of our applications. In additions, BunnyBus can support something like a notification system since subscriptions can be created with non durable and short lived queues so messages can be routed to Socket.io edged services.</p><h3>About the Author</h3><h4>Lam Chan</h4><p>Lam is a Software Architect for the Locals Squads @ XO Group. He is a seasoned polyglot engineer with over 16 years of professional <br>experience working with startups and multiple fortune 500 companies. When he is away from the office, he enjoys contributing to OSS <br>projects and dabbles with wood working projects. Find out more about Lam on <a href="https://www.linkedin.com/in/lamchan">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9647f6283e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>