<?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 João Parreira on Medium]]></title>
        <description><![CDATA[Stories by João Parreira on Medium]]></description>
        <link>https://medium.com/@jparreira?source=rss-ca1f54dde198------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AEF4rYGI4sNRQ0nPfcOEyA.jpeg</url>
            <title>Stories by João Parreira on Medium</title>
            <link>https://medium.com/@jparreira?source=rss-ca1f54dde198------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:05:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jparreira/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[Solving the “Wolf, Sheep and Cabbage” problem using TLA+ and the TLC model checker]]></title>
            <link>https://medium.com/@jparreira/solving-the-wolf-sheep-and-cabbage-problem-using-tla-and-the-tlc-model-checker-28271a5afdfc?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/28271a5afdfc</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[logic]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Tue, 11 Jul 2017 21:51:22 GMT</pubDate>
            <atom:updated>2017-07-11T21:51:22.862Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I bumped into a Microsoft Research talk by Leslie Lamport, named “<em>Thinking above the code</em>”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-4Yp3j_jk8Q%3Fstart%3D1842%26feature%3Doembed%26start%3D1842&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-4Yp3j_jk8Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-4Yp3j_jk8Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d1a0fb65eb4534363eba93c96c7e4b/href">https://medium.com/media/a1d1a0fb65eb4534363eba93c96c7e4b/href</a></iframe><p>As a software engineer with over 20 years of experiencing, I’ve always assumed that describing systems formally with mathematics was all well and good for academic environments, not for real world companies and businesses.</p><p>Leslie’s talk and some of the real-world examples he presented made me think twice. Namely the existence of a model checker made me think twice.</p><p>If TLA+ delivers as “advertised”, you could write your formal specification and verify it using Leslie’s TLC model checker. As stated in the talk, some big real-world companies found subtle bugs in their algorithms while they were still in the design phase, before a single line of code was written. And when I say big companies I mean companies like Amazon, Microsoft and even IBM.</p><p>Formal specification seemed to be working for these big guys so I decided to learn <a href="http://lamport.azurewebsites.net/tla/tla.html">TLA+</a>, Leslie’s specification language containing “as little as possible beyond what is needed to write simple mathematics precisely”.</p><h3>Learning TLA+</h3><p>Leslie has a small <a href="http://lamport.azurewebsites.net/video/videos.html">video course</a> online, so I started there. It was way funnier than I imagined!</p><p>Leslie is a great teacher, with an awesome sense of humor and a wide selection of hats and sun glasses — <em>see the course videos and you’ll understand why :)</em></p><p>If you know your way around simple boolean logic, state-machines and the concepts in mathematical sets and their operators, you’ll find out that as soon as you conquer some of the cumbersome ASCII notations, you’ll be able to read most of the specs available and even write your own.</p><p>The documentation seems hard to understand, with many formal proofs, but if you don’t give up at a first read, you’ll find out that with time you learn how to skip some of the hard proofing parts and learn the essentials semantics to write your own specs.</p><p>As times goes by and you need to gain more “vocabulary” to express your algorithms, you can go back to the documentation and suddenly some of the hard proofs become more understandable. Your brain automatically enters the “math” zone when you start writing TLA+ specs.</p><h3>Solving a problem with TLC</h3><p>I learn better through examples, so following Leslie’s lead with the “Die Hard” problem solution, I have decided to write a specification in TLA+ that could solve the “Wolf, Sheep and Cabbage” problem.</p><p>The problem is defined as follows:</p><ol><li>A boatman has a wolf, a sheep and a cabbage on one side of the river and he must cross them to the other side.</li><li>He can only take one item in each trip between the river banks</li><li>He cannot leave the wolf and the sheep alone, as well as the sheep and the cabbage alone. Otherwise the wolf will eat the sheep and the sheep will eat the cabbage.</li></ol><p><strong>The problem solution is the right sequence of crossings the boatman needs to perform to cross all the items safely.</strong></p><p>This means we can use TLC model checker to check the state tree for a viable branch where the desired state is reached (all items crossed safely). This is easily obtained by configuring a model with an invariant function. If the invariant function evaluates to FALSE at a given state, TLC will show you the state trace (the steps) required to reach that state (the solution).</p><p>Since TLC uses a breadth-first search, the sequence of steps will be the shortest path to the solution.</p><h3>The state machine</h3><p>In TLC you define a state machine by defining the initial state and all the possible steps to change the current state.</p><p>In the “wolf, sheep and cabbage” problem the initial state is “the wolf, the sheep, the cabbage and the boatman, are all in one bank of the river (let’s assume it’s the left bank).</p><p>To change from the current state (in fact, any state) to the next state we have the two following steps:</p><ol><li>The boatman crosses with an item</li><li>The boatman crosses alone</li></ol><p>In order for the boatman to be able to cross with an item (aka payload), he must select one, keeping in mind that the wolf cannot be left alone with the sheep and the sheep cannot be left alone with the cabbage.</p><p>With this in mind we can add a new action to our list, “Select an item to cross”.</p><p>These are the final possible steps:</p><ol><li>The boatman selects an item to cross</li><li>The boatman crosses with a selected item</li><li>The boatman crosses alone</li></ol><p><em>From now on I’ll assume you already know the </em><a href="http://lamport.azurewebsites.net/tla/summary-standalone.pdf"><em>basics of TLA+ notation</em></a><em>.</em></p><p>Let’s start with our state variables. These are the variables required to describe a given state of our problem state machine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec2a07282c5d95b4324af6b8997265e/href">https://medium.com/media/fec2a07282c5d95b4324af6b8997265e/href</a></iframe><p>The trivial definition of the initial state is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a9eb11a9811dfab7cf806413629267d/href">https://medium.com/media/9a9eb11a9811dfab7cf806413629267d/href</a></iframe><p>This means that in the initial state all items are on the left bank of the river, no item was yet selected to transport (the payload), and obviously no item was transported on the previous step (since there was none).</p><p>Now let’s define our first action, “<em>The boatman selects an item to cross</em>”.</p><p>We know the boatman can only select an item from the current bank (the bank where he currently is), but not just any random item. It must be an item such that the remaining items are allowed to be left alone in the river bank when the boatman leaves to cross the river.</p><p>The predicate <strong>Allowed </strong>asserts if a certain set of entities are allowed to be left alone, and it can be trivially defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ca8487c9918d11f6520d7c48a7333cf/href">https://medium.com/media/1ca8487c9918d11f6520d7c48a7333cf/href</a></iframe><p>Notice that leaving all items alone is not allowed by our problem rules, since the wolf would start eating the sheep that would be eating the cabbage!</p><p>Now that we have a predicate asserting if a given set of items are allowed to be left alone, we can specify our <strong>SelectPayload</strong> action rules as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bb79e2004501d678cc6f388306dd4ee/href">https://medium.com/media/4bb79e2004501d678cc6f388306dd4ee/href</a></iframe><p>Using the existential quantifier we can express that the payload selected for transport (<em>payload’</em>), can only be considered if the set resulting from removing it is an allowed set, otherwise the payload is not valid and the step is not possible according to our rules. The TLC model checker will search for another item according to the existential quantifier that enables the state transition.</p><p>It’s also important that the item transported in the previous step (state variable <em>last</em>) is not transported back in the immediate step, since this would be simply “undoing” the current state. This condition will significantly reduce the number of possible states.</p><p>If no item is found and we are not yet in the solution state, the boatman has no other option than crossing the river alone to pick another item from the other river bank.</p><p>Now that we have selected (or not) an item to transport we can trivially define the <strong>CrossAlone</strong> and <strong>CrossItem</strong> steps as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bdad392044f5c876f56df607e0ba0cb/href">https://medium.com/media/0bdad392044f5c876f56df607e0ba0cb/href</a></iframe><p>Since crossing means toggling the boatman current margin, we defined a simple function <strong>OtherBank</strong> that will return the opposite bank name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1279a14b17df4d8e142790b4c340552/href">https://medium.com/media/d1279a14b17df4d8e142790b4c340552/href</a></iframe><p>Our next-state action is a simple disjunction of all the possible steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33aa671957c782189430d35043218e7a/href">https://medium.com/media/33aa671957c782189430d35043218e7a/href</a></iframe><h3>Defining the consistency invariant</h3><p>Now that we have our state machine rules defined, let’s define a function that guarantees our model consistency. This function must be an invariant throughout the model checking. If at any time we get into a state where the function is not true, then we have an error in our algorithm.</p><p>The <strong>ConsistencyOK</strong> function can be defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3973ca625658b0644024ca8e228003ad/href">https://medium.com/media/3973ca625658b0644024ca8e228003ad/href</a></iframe><p>These three things must be true for every single state:</p><ol><li>The boatman can only be in one of the river banks, left or right</li><li>The total number of items in the two banks must always be 3</li><li>The items left alone in the other bank (where the boatman is not present) must be an allowed set of items</li></ol><h3>Defining the solution found assertion</h3><p>To solve this problem we will use the TLC model checker ability to verify if a given function is an invariant through the states checked. This means that if we define a function that is false when our solution is found, TLC will report it as an error and we will be able to inspect the error trace. This error trace will be the steps sequence required to reach the solution.</p><p>This invariant function, <strong>SolutionNotFound</strong>, can easily be defined as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc6bcc316b13523294c38a16f5309a2/href">https://medium.com/media/2fc6bcc316b13523294c38a16f5309a2/href</a></iframe><p>Assuming our model is consistent (assured by the <strong>ConsistencyOK </strong>invariant<strong>)</strong>, if the left bank is empty then it implies all items are in the right bank as we intended and we have found our solution.</p><h3>The specification pretty-print</h3><p>The TLA+ Toolbox has a nice pretty-print feature that makes the spec a little bit easier to read. Here is our specification pretty-print as generated by the Toolbox:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*h0o2IYAoax2mu2CaVexR1A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*m7VZrVyZJQcqGlyj9a9mXw.jpeg" /></figure><h3>Finding the solution</h3><p>In order to use the TLC model checker to find the solution to the boatman problem we just need to create a specification and a model in the Toolbox.</p><p>The full ASCII version of the specification is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a64fc8a8ef7b6e9a6e486d722fc62cce/href">https://medium.com/media/a64fc8a8ef7b6e9a6e486d722fc62cce/href</a></iframe><p>In the Toolbox model overview we need to enter our initial predicate and next-state relation as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*R_816eU06lhrIMgd6J0vUA.png" /></figure><p>Don’t forget to define the invariants also:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*xWl-k6fFzmJBDFWNP58vEA.png" /></figure><p>We are now ready to check our model and find our solution. Select the <strong>Run Model</strong> option from the Toolbox <strong>TLC Model Checker</strong> menu.</p><p>After a few seconds we get an error saying that “<em>Invariant SolutionNotFound is violated</em>”.</p><p>Great! This means we have a solution in the “error” trace.</p><p>In the “Error-Trace” output window scroll-down to the last state listed, the state where the invariant failed. Inspecting the <strong>log</strong> state variable will give us the sequence of steps to reach the solution, and it will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*fYhv5BFi2dp-VgcJ4kzgVQ.png" /></figure><p>From this inspection we learn that the solution steps sequence is the following:</p><ol><li>Cross the sheep</li><li>Cross alone</li><li>Cross the wolf</li><li>Cross the sheep</li><li>Cross the cabbage</li><li>Cross alone</li><li>Cross the sheep</li></ol><p>By inspecting the right bank state variable we verify that indeed all items were successfully crossed from left to right, without breaking the rules we have defined.</p><p>Who said math can’t be fun? :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28271a5afdfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Receiving AWS IoT messages in your browser using websockets]]></title>
            <link>https://medium.com/@jparreira/receiving-aws-iot-messages-in-your-browser-using-websockets-9b87f28c2357?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b87f28c2357</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Thu, 12 Nov 2015 19:17:09 GMT</pubDate>
            <atom:updated>2015-11-12T19:30:07.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQegSwHQWFRuGYufAcBuNA.png" /></figure><h4>Along with AWS Lambda and the Realtime Messaging Platform</h4><p>A few weeks ago AWS launched an interesting cloud service enabling secure, bi-directional communication between Internet-connected things (such as sensors, actuators, embedded devices, or smart appliances) and the AWS cloud over MQTT and HTTP.</p><p>With this service you can easily publish and receive messages from your “things”. But what if you need to receive those messages in a web page using Chrome or Safari? For example to build a web dashboard?</p><p>Well, you can’t … at least using only the AWS IoT SDKs.</p><h4>Enter Realtime Messaging</h4><p>The <a href="http://framework.realtime.co/messaging">Realtime Messaging Platform</a> allows you to build web applications that can receive messages sent from other applications directly in the user’s browser (or mobile device). Using the Realtime JavaScript SDK and the websocket protocol sending and receiving messages in the browser is a few API calls away.</p><p>Imagine we could capture an AWS IoT message and simply send it to a given Realtime pub/sub channel so the web browser subscribers could receive it? It’s not only doable but it’s very easy. We just need a way to capture the AWS IoT message.</p><h4>Enter AWS Lambda</h4><p>AWS Lambda is a compute service where you can upload your code to AWS Lambda and the service can run the code on your behalf using AWS infrastructure. Binding the code you upload to an event, like “new message from AWS IoT”, will allow you to call the Realtime RESTful API in order to publish the message to the appropriate Realtime channel. That simple.</p><p>Now we only need a way to bind our Lambda code (in this example a Node.JS function) to the AWS IoT message broker.</p><h4>Enter the AWS IoT rules</h4><p>One of the coolest parts of AWS IoT is the rules engine as it provides message processing and integration with other AWS services. You can use a SQL-based language to select data from message payloads, process the data, and send the data to other services, such as AWS Lambda. Voilà!</p><p>Defining a rule that invokes the Lambda function when a new message is sent is the last piece in our puzzle:</p><p>Message published in AWS IoT &gt;&gt; Invoke Lambda function &gt;&gt; Send message to Realtime &gt;&gt; Deliver message to web browser subscribers</p><h4>Making it work</h4><p>The AWS IoT provisioning is not a walk in the park but AWS provides a nice <a href="http://docs.aws.amazon.com/iot/latest/developerguide/iot-quickstart.html">step by step quickstart guide</a>. Follow this guide until you reach the “Configure and Test Rules” section.</p><p>If you’re there it means you can successfully publish and receive messages using your “thing” through the <a href="http://mqttfx.jfx4ee.org/">MQTT.fx JavaFX-based MQTT client</a>.</p><h4>Creating the AWS Lambda function</h4><p>In order to send the AWS IoT message to the Realtime Platform we’ll need to write a Lambda function. In our example this function will send the AWS IoT message to the <strong>aws-iot</strong> Realtime channel.</p><p>Using the <a href="https://console.aws.amazon.com/lambda/home?region=us-east-1#/functions">AWS Lambda console</a> click the “Create a Lambda function” button (if you already have other functions defined) or the “Get Started Now” button (if it’s your first Lambda function).</p><p>Since I’ll be giving you the full code ahead you can skip the “Select blueprint” stage by clicking the “Skip” button in the page bottom.</p><p>Now it’s time to configure our Lambda function.</p><p>Enter <strong>iot_to_realtime</strong> in the name input field and copy/paste the following Node.js code into the “Lambda function code” text-area:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8760b05e1191f42631e4adfe70ade32/href">https://medium.com/media/b8760b05e1191f42631e4adfe70ade32/href</a></iframe><p><em>Note: Before proceeding you need to enter your Realtime appkey and private key in the function code above. If you don’t have a Realtime subscription yet you can get a free one at </em><a href="https://accounts.realtime.co/signup/"><em>https://accounts.realtime.co/signup/</em></a></p><p>Keep <em>index.handler</em> in the <strong>Handler</strong> input field and select the “Basic execution role” in the <strong>Role</strong> dropdown. On the <strong>Role</strong> page choose <strong>Allow</strong>.</p><p>Back to the new function page choose <strong>Next</strong> and then <strong>Create Function</strong>.</p><p>On the page displayed, make a note of the function ARN. You will need it to create the AWS IoT rule.</p><h4>Creating the rule to invoke the Lambda function</h4><p>Now that we have the Lambda function ready it’s time to create the AWS IoT rule that will invoke the function when a message is published in <strong>test/topic</strong>.</p><p>In your text editor enter the following JSON document describing your new rule, entering your Lambda function ARN in the <strong>functionArn</strong> property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb49bd8fbe1fa6fb491ea486732c4c58/href">https://medium.com/media/cb49bd8fbe1fa6fb491ea486732c4c58/href</a></iframe><p>Save the document as <strong>aws_iot_rule.json</strong> and run the following AWS CLI command to create the topic rule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f9c4fc80fd7f806196f605a1029f336/href">https://medium.com/media/6f9c4fc80fd7f806196f605a1029f336/href</a></iframe><p>The rule is now created and all we need to do is give permission for the AWS IoT engine rule to invoke the Lambda function. This is done through the following AWS CLI command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80f296d7768cabefc0f4f80646d2c7aa/href">https://medium.com/media/80f296d7768cabefc0f4f80646d2c7aa/href</a></iframe><p><em>NOTE: You can easily extract your AWS Account ID from the function ARN (it’s the number before :function).</em></p><p>If all went well you got a JSON response from the AWS CLI and we are ready to test the AWS IoT/Realtime integration.</p><h4>Bringing it all together</h4><p>To test the AWS IoT/Realtime integration let’s start by subscribing the <strong>aws-iot</strong> channel in a web browser.</p><p>Open the <a href="http://console.realtime.co/">console.realtime.co</a> page in your preferred browser, enter your Realtime application key and click the <strong>connect</strong> button.</p><p>Your browser is now connected to a Realtime server and you are ready for subscribing data channels.</p><p>Now enter <strong>aws-iot</strong> in the channel input field and click the <strong>subscribe</strong> button.</p><p>You should be seeing something like this in your Realtime Console Log panel:</p><p><em>16:26:23 — SUBSCRIBED TO: aws-iot<br>16:26:23 — SUBSCRIBING TO: aws-iot…<br>16:24:59 — HEART BEAT DETAILS: Active — false | Time — 15 | Fails — 3<br>16:24:59 — USING: websocket<br>16:24:59 — SESSION ID: fceda1653cfb0241<br>16:24:59 — CONNECTION METADATA:<br>16:24:59 — CONNECTED TO: http://ortc-developers2-euwest1-s0001.realtime.co<br>16:24:58 — CONNECTING TO: </em><a href="http://ortc-developers.realtime.co/server/2.1..."><em>http://ortc-developers.realtime.co/server/2.1...</em></a></p><p>If you do see something like this it means you are subscribed to the channel.</p><p>Now we need to send a message from our AWS IoT “thing” using the MQTT.fx client (or any other MQTT compatible client).</p><p>Open the MQTT.fx client and connect to AWS IoT (you can follow this <a href="http://docs.aws.amazon.com/iot/latest/developerguide/verify-pub-sub.html">AWS IoT guide</a>).</p><p>After connecting, select the <strong>Publish</strong> tab, enter <strong>test/topic</strong> in the topic input field and a JSON message like this in the message field:</p><p>{“message”:”Hello World”}</p><p><em>NOTE: if the message is not a well formed JSON object the Lambda function call will fail and no message will be sent to the Realtime server.</em></p><p>Now click the <strong>Publish</strong> button.</p><p>In your console.realtime.co browser window you should see the following log in the Log panel:</p><p><em>18:41:09 — RECEIVED AT aws-iot: {“message”:”Hello World”}</em></p><p>This means your AWS IoT “thing” message was delivered to your browser through the Realtime Platform. Yes!</p><h4>What next?</h4><p>This is simply a proof-of-concept but you can see the power behind it.</p><p>Imagine your AWS IoT “thing” is a temperature sensor that is publishing the current room temperature to an AWS IoT topic. With this approach you could relay these temperature messages to a web dashboard showing a real-time updated chart with the read values.</p><p>This approach allows any AWS IoT messages to be sent over the internet to browsers and mobile applications with a few simple configurations and you don’t need to run absolutely no server at all.</p><p>It’s the “serverless” brave new world.<br>Now it’s up to you and your imagination.</p><p>Go build :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b87f28c2357" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Realtime “why, how, where, who and when” in less than 5 minutes]]></title>
            <link>https://medium.com/@jparreira/the-realtime-why-how-where-who-and-when-in-less-than-5-minutes-59a82154d621?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/59a82154d621</guid>
            <category><![CDATA[pitching]]></category>
            <category><![CDATA[messaging]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Tue, 26 May 2015 09:58:42 GMT</pubDate>
            <atom:updated>2015-05-26T09:58:42.660Z</atom:updated>
            <content:encoded><![CDATA[<h4>Or how Theo Priestley made me stop and think about my product story</h4><p>Yesterday I’ve read a great post from Theo Priestley about “<a href="https://www.linkedin.com/pulse/why-silicon-valley-tech-companies-cant-tell-own-story-theo-priestley">Why Silicon Valley Tech Companies Can’t Tell Their Own Story</a>”.</p><p>He said:</p><blockquote>Tech companies really struggle to get away from the product detail and just tell a story.</blockquote><p>Guilty as charged.</p><p>As the CTO for the <a href="http://framework.realtime.co/">Realtime Platform</a>, Tech Evangelism is a good part of my job and Theo’s words made me think I was probably falling into the same trap he so wisely mentions in his post.</p><p>Is my “<em>deep technical passion in the product itself</em>” not allowing “<em>the solution to come alive</em>”?</p><p>Are the new prospects sitting in front of me misunderstanding the Realtime “story” because I’m not being clear on the “<em>why, how, where, who and when</em>” behind the Realtime Platform Services?</p><p>Theo urged Tech Evangelists to tell him:</p><blockquote><strong>why</strong> your product exists<br><strong>how</strong> it can resolve a pain or need, and <strong>how</strong> it can make a difference<br><strong>where</strong> the value in using the solution or service comes from<br><strong>who</strong> will it help the most, and <strong>who</strong> has it already helped<br><strong>when</strong> can I get my hands on it, and <strong>when</strong> will it make a difference</blockquote><p>Well AFAIC, the challenge was accepted.</p><p>This post is a tech guy attempt of telling you the Realtime Messaging story in less than 5 minutes (I know Theo didn’t define a maximum “story-telling” time but I’m guessing he has a busy life …)</p><h3>Why Realtime Messaging exists</h3><p>Mobile apps and websites are becoming increasingly collaborative. Users expect to be able to interact in real-time with live data and with other users in the context of that data. Whether it’s a TV channel second-screen mobile app, a multi-player online game or a line-of-business team management website, just to mention a few use cases.</p><p>This intensive collaboration between users means millions of messages being routed through global networks in a split second. It requires scalable, secure and fast communications between different devices with different capabilities. From powerful laptops to small sensors and trendy wearables.</p><p>The Realtime Messaging exists as a cloud service to enable this inter-device communication in a simple and cost effective way.</p><h3>How it can resolve a pain or need, and how it can make a difference</h3><p>Scalability is hard and cannot be an afterthought. Apps must be ready to scale when demand spikes and users will be quite unforgiving for sluggish apps that just won’t work properly every single time.</p><p>In Realtime we often see companies complaining that they have built their own messaging platforms, sometimes using popular open-source software, and while everything was working perfectly in the development and testing stages, failed blatantly under real production load.</p><p>In the midst of all this pain they have found themselves draining precious resources and attention that should have been used to improve their app’s unique features instead.</p><blockquote><strong>Focus is about saying no.</strong><br>Steve Jobs</blockquote><p>The Realtime Messaging service is auto-scalable and already handles over 500 million monthly active users. It can remove your scalability pains and return your team focus to what really matters, your app and your distinctive features.</p><p>Understanding that you don’t need to build the entire software stack yourself can make a lot of difference between launching or ditching your app with a bang.</p><h3>Where the value in using Realtime Messaging comes from</h3><p>Every minute in the Realtime Messaging Engineering team is spent improving performance, availability and the ability to scale at huge scale, while delivering the results through a simple cloud service with a clear API.</p><p>It’s a specialized work made my specialized people.</p><p>Use the Realtime Messaging service in your app and this specialized engineering team will be a part of your specialized team too. This has great value.</p><p>Our experience and know-how, embodied in the services we develop and manage, will be yours too. The fact that this battle hardened experience will be free while you are in the development stages of your app has great value.</p><p>The fact that it will reduce your overall cost of ownership when you’re ready for production has great value.</p><p>The fact that Realtime solves your inter-device messaging problems with a ready-to-use API, embodying modern security and state-of-the-art distributed infrastructure has lots of value.</p><h3>Who will Realtime help the most and who has it already helped</h3><p>Startups love Realtime for the competitive pricing.<br>Corporate companies love Realtime for the high-availability through multiple data-centers.<br>Both love Realtime for the performance and extensive feature set.</p><p>During these 4 years since launching Realtime helped startups and corporate companies around the world building engaging modern apps where inter-device communication is at the core.</p><p><a href="http://webspectator.com/">WebSpectator</a>, <a href="https://www.buddytruk.com/">BuddyTruk</a>, <a href="http://emplo.com/en/home/">Emplo</a>, <a href="http://ig.com.br/">IG</a>, <a href="http://www.playrix.com/">Playrix</a>, <a href="http://www.keradgames.com/">Kerad Games</a>, <a href="http://economico.pt/">Diário Económico</a>, <a href="http://www.hereon.biz/">HereOnBiz</a>, <a href="http://tenacreapps.com/">TenAcreApps</a>, <a href="http://www.bb.com.br/">Banco do Brasil</a>, <a href="http://www.ptsgps.pt/en-us">Portugal Telecom</a>, <a href="https://www.meo.pt/">MEO</a> and <a href="http://nos.pt/">NOS</a> are just a few examples taken from the 5,000+ live apps using Realtime today.</p><p>Some are startups in their first year. Others are corporate companies leading their markets. One is a leading internet portal and another is even the largest Latin-American bank with 40 million clients and 85 billion US Dollars in assets. A heterogeneous group of great customers.</p><p>Some pay only a few dollars per month. Some a few thousand.</p><p>Some didn’t have the funds to develop a full-fledged scalable messaging platform. Some had, but couldn’t afford the long time to market. Some knew it’s not wise to reinvent the wheel.</p><p>The bottom line is they all have great engaging collaborative apps, from games to home-banking tools. All using Realtime.</p><h3>When can I get my hands on it, and when will it make a difference</h3><p>Realtime Messaging is a cloud service with a pay-as-you-go pricing structure and a free development tier. You only pay for what you really use.</p><p>Simply subscribe the free plan at <a href="https://accounts.realtime.co/signup/">https://accounts.realtime.co/signup/</a> and start using it. No strings attached.</p><p>Now it would be a good time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59a82154d621" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling to 500 million monthly unique users]]></title>
            <link>https://medium.com/@jparreira/scaling-to-500-million-monthly-unique-users-16689c9b145c?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/16689c9b145c</guid>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Wed, 22 Apr 2015 20:14:52 GMT</pubDate>
            <atom:updated>2015-04-22T20:14:52.835Z</atom:updated>
            <content:encoded><![CDATA[<h2>Scaling to 500 million monthly active users</h2><h4>How Realtime is helping WebSpectator.com change digital advertisement</h4><p><a href="http://webspectator.com/">WebSpectator.com</a>, the world’s first time and engagement advertising solution for mobile &amp; web, uses the <a href="http://framework.realtime.co/messaging">Realtime Messaging Platform</a> to connect to their 500 million unique users around the globe.</p><p>For WebSpectator.com “time is money” is more than just words, it’s a proven fact. Each second they are increasing their INC.500 publisher’s Ad revenue by monetizing the time users spend using their websites and mobile apps.</p><p>The Realtime Messaging Platform is proud to be powering the patented revolutionary WebSpectator technology from their first page-view to their staggering 3.3 billion page-views last month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*IyRXBAbuHZ-gshhKSWm3PQ.png" /><figcaption>WebSpectator’s last month quantified metrics by Quantcast</figcaption></figure><p><a href="https://www.quantcast.com/p-HGAVM7nQJ_sep?country=GLOBAL"><em>https://www.quantcast.com/p-HGAVM7nQJ_sep?country=GLOBAL</em></a></p><h4>Why real-time?</h4><p>In simple terms, WebSpectator allows advertisers to know the exact amount of time users spent seeing their ads and never charges for unseen ads. To achieve this unprecedented level of control, WebSpectator needs to know which ads are visible in the user’s screens. For each ad. For each user.</p><p>On top of all these strict business requirements, in order to keep up with the advertising industry accreditation standards, all “effective exposure time monetization” logic must be computed in WebSpectator’s backend servers, never at the client. This means they need to ingest all the data triggered by the users events in real-time. And it’s a lot of data per second.</p><h4>Big websites. Big data. Small infrastructure.</h4><p>By leveraging the Realtime Messaging Platform, WebSpectator keeps infrastructure costs down and focus on their core-business.</p><p>Instead of worrying on managing the required infrastructure to scale to hundreds of thousands of concurrent users while keeping proper support for all browsers and mobile platforms, WebSpectator can simply focus on improving the features their advertisers and publishers love so much.</p><p>And when you aggregate high-profile publishers like <a href="http://forbes.com/">Forbes</a>, <a href="http://tmz.com/">TMZ</a>, <a href="http://www.condenastinternational.com/">Condé Nast</a>, <a href="http://abcnews.go.com/">ABC News</a> and <a href="http://www.wired.com/">Wired </a>— just to mention a few — all with high-traffic digital properties, web and mobile, the number of concurrent users is always high and the number of events they generate is higher, normally tens of thousands per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkl26SnAhqHUsBa48fNmuQ.png" /><figcaption>A Realtime Messaging connection in Forbes.com</figcaption></figure><p>The role of the Realtime Messaging Platform in WebSpectator’s stack is to establish a full-duplex connection to each user of those digital properties — WebSockets whenever possible — to receive the user events and deliver them to the WebSpectator backend servers for processing. Whenever the WebSpectator backend needs to retrieve some user specific data it simply publishes a command in the appropriate pub/sub channel and the Realtime Messaging Platform routes and delivers it to the targeted user in a few milliseconds. The same happens with the client command reply.</p><p>The Realtime Platform is also responsible for the infrastructure scaling, so WebSpectator doesn’t need to worry if all of a sudden some digital publisher has just published some viral content and their traffic is 10x or 100x the normal traffic. They rest assured every user will be connected with the least latency possible and no single advertisement dollar will be lost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ja0J5XjilIPeXui12m0_9w.png" /><figcaption>A Realtime Messaging connection in Wired.com</figcaption></figure><p>Also by using the Realtime Messaging Platform as a communication abstraction layer, the WebSpectator components only have to deal with their own protocol and can be oblivious of the methods and protocols used to ingest and broadcast data in non-homogeneous and sometimes unstable internet networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*8GZlwiW4IbJGiLuUiRCc8Q.jpeg" /><figcaption>The TMZ app: The Realtime Messaging connection must work in WebSpectator customers mobile apps, even with unstable internet connections</figcaption></figure><p>By not having to deal with these methods and protocols the WebSpectator backend components become faster and less resource-hungry, reducing the infrastructure costs. The overall architecture becomes simpler and easier to maintain.</p><h4>Do what you do best and outsource the rest</h4><p>The advice from the legendary business consultant Peter Drucker still holds today and in this “<em>there’s-a-service-for-that”</em> world we are living in, it’s truer than ever before. And simpler to do.</p><p>Innovative companies like WebSpectator need to move fast and invest hard on their unique value proposition. There’s no time to be lost re-inventing the wheel, specially developing services that are already commodities — you don’t build you own electric grid so why should you build your own messaging platform?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*esYtR3qQafe_ls6ZHQFe4A.jpeg" /></figure><p>To achieve their goals, these lean-and-mean companies need to find the right partners with the same highly-focused DNA. Today it makes no sense coding all levels of the stack when there are already great specialized services available. These services probably do a better job than your engineering team would do, not because they’re better engineers but because it’s their core-business and they are focused in it — just like you are focused in yours.</p><p><strong>With the right partners the value chain can be so much more than the sum of its parts and can introduce serious industry disruption. That’s exactly what WebSpectator is doing in the digital advertisement industry and Realtime is proud to be a part of that.</strong></p><p>—</p><p><a href="http://framework.realtime.co/"><em>Know more about what the Realtime Platform can do to accelerate your business</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16689c9b145c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating REST APIs with webhooks and Realtime Code Hosting]]></title>
            <link>https://medium.com/@jparreira/integrating-rest-apis-with-webhooks-and-realtime-code-hosting-bf57eb381ee1?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf57eb381ee1</guid>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Thu, 02 Apr 2015 11:09:09 GMT</pubDate>
            <atom:updated>2015-04-02T11:20:05.285Z</atom:updated>
            <content:encoded><![CDATA[<h4>Get a Twilio SMS whenever someone comments in your Trello boards</h4><p><a href="http://realtime.co/">Realtime</a>, the company I work for, recently launched a new managed cloud service called <a href="http://storage-public.realtime.co/documentation/code-hosting-guide/1.0/overview.html">Realtime Code Hosting</a>.</p><p>In a nutshell it allows you to host a REST API using an auto-scalable cloud platform. You write your API logic using Node.js JavaScript code, push the scripts to the Realtime Code Hosting Platform and you’ll instantly get HTTP/HTTPS REST endpoints to invoke the API.</p><p>Use these endpoints as callback URLs and you’ll easily integrate with third-party platforms providing webhook integration (a webhook is a method of augmenting or altering the behavior of a web page, or web application, with custom callbacks).</p><p>Let me give you a practical example.</p><p>You’re starting a new project with some friends and you need a web platform to keep control of what’s being worked on, who’s working on what, and where something is in the process. Since you aren&#39;t always connected to this platform 24/7, you want to receive real-time notifications in your phone whenever someone contributes to any particular task.</p><p>Challenge accepted.</p><p>First you’ll need to select a web collaboration tool. Enter <a href="http://trello.com/">Trello</a>.</p><p>Trello is team collaboration tool that lets you organize anything and everything to keep your projects on task. Since Trello allows you to define a set of webhooks to receive notifications when a model changes (e.g. a board or a card), you just need to configure a Realtime Code Hosting REST API route to receive these notifications and when appropriate send a SMS message with the comment text.<br>SMS? Enter <a href="https://www.twilio.com/">Twilio</a>.</p><p>Twilio is an easy tool for developers to send and receive SMS and voice calls. It also provides a very simple REST API.</p><p>For our use case we’ll configure Trello webhooks to call our Realtime Code Hosting API and when the action is a new comment we’ll call the Twilio REST API to send the SMS. Easy.</p><h4>Realtime Code Hosting configuration</h4><p>The <a href="http://storage-public.realtime.co/documentation/code-hosting-guide/1.0/overview.html">Realtime Code Hosting starting guide</a> has all the details about activating your own Realtime Code Hosting Platform for free. For the sake of simplicity I’ll assume you already have activated your Realtime Code Hosting Platform and I’ll jump forward and create a REST route endpoint named <em>trelloComment</em>.</p><p>As a matter of fact we’ll need two endpoints with that name, since Trello will call one of them using the HTTP HEAD method when you’re setting the webhook (for validation purposes) and later will use a HTTP POST to notify you of model changes. All the details, including our comment text, will be in this POST request body.</p><p>The HEAD <em>trelloComment</em> script simply returns a 200 status code so Trello accepts the webhook callback URL. The Realtime Code Hosting JavaScript code will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d0aa90b6a60ae2dfb0c6dd47e351bfc/href">https://medium.com/media/5d0aa90b6a60ae2dfb0c6dd47e351bfc/href</a></iframe><p>The POST <em>trelloComment</em> script will be a bit longer since we need to validate if the triggered action is a new comment. If that is the case we’ll call the Twilio API to send the SMS message (you can check the Twilio Messages API details at <a href="https://www.twilio.com/docs/api/rest/sending-messages">https://www.twilio.com/docs/api/rest/sending-messages</a>).</p><p>The JavaScript code will look like this (don’t forget to enter your Twilio account credentials and phone number in the appropriate places):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a31f4036bd508eeb5cebe8b0123195e2/href">https://medium.com/media/a31f4036bd508eeb5cebe8b0123195e2/href</a></iframe><p>As soon as you push your <em>trelloComment</em> script to the Realtime Code Hosting Platform you’ll have a REST endpoint that will look like this:</p><p><em>https://codehosting.realtime.co/[REALTIME_APPKEY]/trelloComment</em></p><p>This will be the URL we’ll define as the Trello webhook callback URL.</p><h4>Trello webhook configuration</h4><p>Configuring Trello webhooks is not a walk in the park but it isn&#39;t rocket science either. You can find more details at the <a href="https://trello.com/docs/gettingstarted/webhooks.html">Trello webhooks documentation</a>.</p><p>Assuming you already have your Trello token, key and idModel (the id of the model that should be hooked), you just need to send a POST to the Trello webhooks API route (it will look like the following one):</p><p><em>https://trello.com/1/webhooks/?key=[YOUR_TRELLO_KEY]&amp;token=[YOUR_TRELLO_TOKEN]&amp;callbackURL=https://codehosting.realtime.co/[REALTIME_APPKEY]/trelloComment&amp;idModel=[YOUR_TRELLO_MODEL_ID]</em></p><p>Note that the callbackURL parameter is your Realtime Code Hosting <em>trelloComment</em> route URL.</p><p>If everything is OK you’ll get a 201 status code with a response stating your Trello webhook id. This means your Trello webhook is set and from now on whenever there is a change in the configured model your Realtime Code Hosting <em>trelloComment</em> route will be called. If the triggered action is a new comment you’ll receive a SMS notification in your phone.</p><p>Success!</p><p>All with just a few lines of JavaScript and without the need of managing any infrastructure whatsoever. Just three great services and APIs working together: Trello, Twilio and Realtime Code Hosting.</p><h4>Wrapping-up</h4><p>This is only a simple example of the level of custom integration between APIs that can be achieved through the Realtime Code Hosting platform. Many more could be presented.</p><p>I hope you found this interesting and that you feel inspired to build your own REST API using Realtime Code Hosting. If you have any interesting use case please share.</p><p>Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf57eb381ee1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using atomic counters to resolve concurrency conflicts in Android game]]></title>
            <link>https://medium.com/@jparreira/using-atomic-counters-to-resolve-concurrency-conflicts-in-android-game-1cd3929482c0?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cd3929482c0</guid>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Tue, 23 Dec 2014 17:43:17 GMT</pubDate>
            <atom:updated>2014-12-23T17:43:17.575Z</atom:updated>
            <content:encoded><![CDATA[<h4>Theory is good, but practice is a lot more fun</h4><p>A few weeks ago I wrote about <a href="https://medium.com/@jparreira/concurrent-mutual-exclusive-actions-using-atomic-counters-7dca3bbd0f1d">using atomic counters to implement mutual exclusive actions in a high concurrency scenario</a>, like an online multi-player game.</p><p>With the help of my eldest son, <a href="https://twitter.com/TheGustash">@TheGustash</a>, we&#39;ve decided to write a simple multi-player Android game that could illustrate in practical terms the strategy defined in my previous post.</p><p>For the data backend we selected the <a href="http://framework.realtime.co/storage/">Realtime Cloud Storage</a> service. Powered by the <a href="http://aws.amazon.com/dynamodb/">AWS DynamoDB</a> database, it has the atomic counters with the added goodies of real-time data-sync between players to make it more fun.</p><h4>A memory map game</h4><p>The game concept is simple: several players use their Android devices to concurrently find the hidden 18 alphanumeric pairs in a 6x6 grid.</p><p>When players select a tile in the grid, the atomic counters are used to find if they won the selection. When they successfully select a tile, the tile content is revealed to all players and the player that selected it has 3 seconds to select a second tile that contains the same content. If they make a pair they win 10 points and the pair of tiles becomes blocked and permanently visible. A failed attempt to finding a pair will decrement 1 point to the current player score.</p><p>Through the use of <a href="http://framework.realtime.co/storage/">Realtime Cloud Storage</a> data-sync feature the players actions are synchronized in real-time and if you are really good and have a great memory you’ll benefit from the other player’s tile selections and not just yours.</p><p>It’s all a question of having a good memory and fast fingers.</p><h4>Using the atomic counter to resolve conflicts</h4><p>Each tile of grid has a counter initialized to the value 1. Whenever players select a tile they subtract the value 1 (one) to the counter and wait for the data store reply. If the reply contains a counter value of 0 (zero) than this means the player was the first one to successfully decrement the counter granting him or her the tile ownership for the moment. Due to the <a href="http://en.wikipedia.org/wiki/Linearizability">atomic properties</a> of the counter all other players that have selected the same tile will have replies with negative values in the counter, so they know they have not conquered the tile and should try another one. The tile conqueror will now be responsible for handling the game logic for that tile.</p><p>From a development point a view it’s a binary <a href="http://en.wikipedia.org/wiki/Semaphore_(programming)">semaphore</a> lock, since in every other device the transactions over that particular tile are “locked” until the winning player resets the counter (thus releasing the semaphore). The cool part is that no one is really blocked in the process, they can continue playing selecting other non-locked tiles.</p><p>The following Gist shows how an atomic counter decrement can be implemented in Java (using the <a href="http://storage-public.realtime.co/documentation/android/1.0.0/">Realtime Cloud Storage Android SDK</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/037c54356c3abbf2bcc4b4f038a935af/href">https://medium.com/media/037c54356c3abbf2bcc4b4f038a935af/href</a></iframe><h4>Running the game</h4><p>The full source code is available at <a href="https://github.com/jparreira/memorygame">https://github.com/jparreira/memorygame</a></p><p>To compile and run it in your device you‘ll need Android Studio 1.0 and a <a href="https://accounts.realtime.co/signup/">Realtime Cloud Storage subscription</a>.</p><p>Using the Realtime Cloud Storage console create two tables with the following key schema:</p><blockquote><strong>Game<br></strong><em>The table Game will store the players in each game along with their individual score.</em></blockquote><blockquote><em>Primary key: gameID, String<br>Secondary key: playerID, String</em></blockquote><blockquote><strong>Tiles<br></strong><em>The table Tiles will store the game tiles (the grid) where each tile is identified by it’s gameID and position in the grid (an x,y coordinate).</em></blockquote><blockquote><em>Primary key: gameID, String<br>Secondary key: coordinate, String</em></blockquote><p>If you prefer you can <a href="https://github.com/jparreira/memorygame/releases/download/0.1/memorygame.apk">download the .apk file</a> and install it manually in your Android device.</p><p>You can play alone in single-mode or invite friends to play with you by sending them your gameID (a 10 digit string that uniquely identifies your game). You can play against a maximum of three friends at a time.</p><h4>Conclusion</h4><p>I just wanted to prove with this simple prototype that you can build concurrent multi-player games and resolve the concurrency conflicts using only client-side code (in this case Java code in an Android device).</p><p>Maybe you feel motivated to build a JavaScript or iOS version. If you keep the same table schema we&#39;ve used in this example, Android players could play against web and iOS players. A true cross-platform memory map game.</p><p>Let me know if you’re up to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cd3929482c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrent mutual exclusive actions using atomic counters]]></title>
            <link>https://medium.com/@jparreira/concurrent-mutual-exclusive-actions-using-atomic-counters-7dca3bbd0f1d?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dca3bbd0f1d</guid>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Mon, 01 Dec 2014 02:30:22 GMT</pubDate>
            <atom:updated>2014-12-01T02:46:26.803Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>A multi-player game scenario</strong></h4><p>Imagine you’re a game developer building a multi-player game and you would like to use client-side code only. You don’t want to write any server-side code let alone manage the required server infrastructure. The game action happens at each player’s device and you’re using some messaging BaaS (e.g. <a href="http://framework.realtime.co/messaging">Realtime Cloud Messaging</a>) to handle the game state sync between players.</p><p>In this game users concurrently compete with each other to get hold of game assets. It could be a weapon, extra-power or some other perk that will increase the player competitive advantage on the game.</p><p>If these assets can only be exclusively awarded to one player in the game you’re bound to face a problem: what happens if two or more players concurrently select the same asset at the same time? You can’t award it to all the contending players so you need to select only one and you need to do it fast in order to keep a great UX. What would you do?</p><h4><strong>Database transactions?</strong></h4><p>You could use a database transaction to read the status of the asset in order to check if it’s still available. If it is you would update the status to <em>granted </em>and commit the transaction. All the other pending transactions would resume and the player would be notified that he or she got the asset. But the keyword here is “pending”. Database transactions use locks and with high-levels of concurrency the UX could suffer from long delays. If several distinct games (e.g. different worlds or universes) were being played at the same time it wouldn&#39;t be difficult to design the database schema in a way where locks from a game would impact users from another game. Not good.</p><h4><strong>REST API with FIFO queue?</strong></h4><p>You could develop a REST API with a route that players would invoke whenever they want to select an asset. This REST API could be distributed into several frontend servers for scalability and each frontend server would push the player intent into a FIFO queue (I’m thinking REDIS). A backend worker would dequeue the intents one at a time and interact with the database using no locks. As you&#39;ve probably spotted, this approach is also locking requests through the queue, so latency increase is expected as the requests frequency increases. But more importantly this approach requires server-side code and infrastructure management, something I&#39;ve said in the beginning that you didn&#39;t want to do, so it’s not really a solution here.</p><h4><strong>Atomic counters</strong></h4><p>In concurrent programming, an operation is atomic if it appears to the rest of the system to occur instantaneously (more at <a href="http://en.wikipedia.org/wiki/Linearizability">http://en.wikipedia.org/wiki/Linearizability</a>). A counter is some numeric property that can be incremented and decremented.</p><p>Given these definitions we could define an atomic counter as a number you can update “instantaneously” (increment/decrement).</p><p>Since the operation is “instantaneous” you don’t care if there are a lot of them happening concurrently because only one update will be performed at a given instant. When these atomic counters are available in a database management system, e.g. <a href="http://framework.realtime.co/storage">Realtime Cloud Storage</a>, you get a powerful primitive to solve the mutual exclusive actions challenge.</p><p>How?</p><p>Each asset in the game is initialized with an atomic counter set to the integer value 1. We set it to 1 because we want to award the asset to only one player in the game (the rational is the same if you want to award the asset to a certain amount of players: just set the atomic counter to the number representing the maximum amount of players that can select the asset).</p><p>Whenever a player wants to select an asset it simply decrements the asset counter and inspects the result. In our case, if the result is 0 then the player gets the asset as it was the first one to capture it. If the result is lower than 0 then the player missed the opportunity as the asset was already awarded to another player.</p><p>The atomic property of the counter plays a crucial part in this solution. As it guarantees that only one decrement occurs “instantaneously” at a time and each player gets the end result of its own decrement, you don’t have to worry about concurrency. The players can all try to select the same asset at the same time but it will only be granted to the first one decrementing the counter. All the others will get negative values.</p><p>In your game logic you just need a simple condition to verify if the asset selection was successful (counter == 0). If that’s the case you can proceed with the asset grant logic in the winning player’s device. In the other players you can simply proceed with the “failed to grab asset” logic (maybe some warning buzz).</p><h4><strong>Using atomic counters-as-a-service with Realtime Cloud Storage</strong></h4><p>As stated before the <a href="http://framework.realtime.co/storage">Realtime Cloud Storage</a> database, based on Amazon DynamoDB, allows you to use atomic counters as-a-service. This means you get all the benefits from the atomic counters at all levels of concurrency, without the need of managing the code and infrastructure that supports them.</p><p>But it gets even better! Through the Realtime Cloud Storage SDKs or REST API you can use the atomic counters directly from the player’s devices! This means “mission accomplished”: concurrent mutual exclusive selections without managing any server-side code and infrastructure.</p><p>Below is the required JavaScript code to implement a basic mutual exclusive <em>selectAsset </em>function using the Realtime Cloud Storage JavaScript SDK:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12a935105a00bb5b34d9d7ec547e7a5d/href">https://medium.com/media/12a935105a00bb5b34d9d7ec547e7a5d/href</a></iframe><h4><strong>Conclusion</strong></h4><p>Atomic counters are a great primitive to control state in multi-player games and using them <em>as-a-service </em>with the <a href="http://framework.realtime.co/storage">Realtime Cloud Storage</a> database is simple and cost-effective. With no server-side code to maintain and no infrastructure to manage you can spend more time improving and adding more features into your game.</p><p>Let me know what you think about this solution and if you have other atomic counters use cases please share, I’d love to hear from you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dca3bbd0f1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Realtime uses Amazon DynamoDB]]></title>
            <link>https://medium.com/@jparreira/why-realtime-uses-amazon-dynamodb-749ffdc957a1?source=rss-ca1f54dde198------2</link>
            <guid isPermaLink="false">https://medium.com/p/749ffdc957a1</guid>
            <dc:creator><![CDATA[João Parreira]]></dc:creator>
            <pubDate>Sat, 29 Nov 2014 12:28:44 GMT</pubDate>
            <atom:updated>2014-11-29T12:38:54.859Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>From a static web to a live web</strong></p><p>In <a href="http://www.realtime.co/">Realtime</a> we believe the static web is a thing of the past and we want to contribute to the necessary change. We’ve decided to create a set of easy to use cloud services that would enable this change, from a static web to a live web, a web where total interaction and engagement with users is performed in real-time, as in life.</p><p><strong>Messaging as the basic building block</strong></p><p>We knew that message-passing would be the underlying building block of this new live web so we started there. Leveraging on the new WebSockets standard while keeping compatibility with older browsers, we developed a global cloud message broker with SDKs for desktop and mobile, providing developers with a layer of pub/sub messaging magic.</p><p>A message published by a user in Singapore could trigger, with a latency of only a few milliseconds, a reaction in another user in New-York using the same application. And vice-versa. The goal was achieved, live engaging web applications can now be easily developed with Realtime Messaging Framework and because it runs in the cloud start-ups and big corporate companies just register, use it and pay-as-they-go, never needing to buy and manage any messaging servers whatsoever. The revolution of the web is underway.</p><p><strong>The live web needs a live database</strong></p><p>During the last two years we have been watching developers being creative and finding innovative ways of using our cloud message broker to power their real-time applications. From interactive digital marketing platforms, to real-time advertising networks, to engaging multi-player games, our cloud message broker has been powering all these use cases.</p><p>But one thing was becoming evident; in most cases those applications would be saving data in some database for persistence purposes and afterwards broadcast the same data through the message broker so the interested subscribers could update their user interface in real-time. These applications could benefit a lot from a database with real-time triggers.</p><p>A database where applications could subscribe to data-changing events and receive messages in real-time with the changed data, as soon as the change occurred.</p><p>This new paradigm of updated data finding its way to the users interested in the change would change for the better the way collaborative real-time applications are developed. In a nutshell it would be the holy grail of collaborative applications: simple real-time data sync among users.</p><p>We had the message-passing building block covered but we still needed to find a scalable database, able to handle the hundreds of thousands operations per second our message broker was handling. The database we needed should not only be scalable but it should also be elastically scalable, scaling in and out according to the different workloads it would be subjected. Naturally it should also be fast, predictable, easy to manage, tolerant to failures, secure and really cost-effective.</p><p><strong>Enter Amazon’s DynamoDB</strong></p><p>We pitched the real-time database sync to one of our largest clients, a global Ad Exchange Network, to validate the opportunity and when you hear a client say “That would make our day, any day!” you know you’re up to something. Time was of the essence and we didn’t have much of it, so we added a new requirement to our database requirements list: it must be a ready-to-use cloud service with a nice SDK so we can wrap our real-time features around it.</p><p>We were inclined to choose Cassandra, namely because it has been in production in many demanding environments for years and had the NoSQL data model that we were so much in love with since we started using Redis in our messaging backend.</p><p>However our time-to-market was short and we needed a managed host service that could reduce the need of infrastructure operations. One that would allow us to focus mainly on the real-time data sync features. We didn’t want to manage Cassandra clusters and certainly didn’t want to manage the required servers.</p><p>At some point of the brainstorming someone mentioned “Amazon’s DynamoDB”. The feature list resembled a lot our requirements list and it was a cloud service, a managed cloud service. On top of it SSDs were being used so probably it would be fast and predictable as our friend Redis.</p><p>We decided to take DynamoDB for a spin and that proved to be a very good decision.</p><p>The API was simple, with good documentation and we’ve come to the conclusion that in DynamoDB we had pretty much the same features we liked in Cassandra: key + columns data model, composite key support, distributed counters and so on.</p><p>We would face a few limitations though, the largest value supported is substantially smaller (400KB in DynamoDB against the 2GB in Cassandra) and the deployment options are more restrictive (DynamoDB could only be deployed inside AWS), but we could engineer around those limitations, at least for the cloud service we wanted to provide.</p><p>Our major concern was the scalability of the service. We were afraid that we might run into problems when scale-ins occur. We’ve heard of a few issues some companies with highly seasonal applications were having with Cassandra clusters when they needed to decommission nodes, facing slow, manual and error prone operations. We couldn’t afford this type of problems so we were afraid DynamoDB could not be up to the task in this domain. But you know what? It was.</p><p>The provisioned capacity units pricing model might not be the easiest to explain to the CEO but technically it’s almost perfect for our current workloads (heavy during the day and evening, lighter late at night). Increase capacity at peak and decrease when off-peak. Dynamo was flawless in all the crazy scale-out and scale-in tests we’ve thrown at it. No data loss requiring restores from backups. And even more important, the application suffered absolutely no downtime during capacity transitions.</p><p>This was a major win, not only we would be able to provide our clients with an awesome real-time data sync but we would also be providing means for them to adjust their database capacity to the demand without any downtime. All this through the use of a simple API call. Perfect in these times where budgets are shrinking and you have to do more with less.</p><p><strong>It can’t be perfect</strong></p><p>“Perfect is the enemy of good”, so they say. And I find that to be very much true. When we started using DynamoDB the indexing options were limited to the Hash and Range attributes. During the development of Realtime Cloud Storage, AWS launched the Local Secondary Indexes with support for up to five local secondary indexes per table, enabling a more efficient retrieval of data. Nice!</p><p>A few things are still missing though. At the time of this writing there’s no means of backing up a table periodically to S3 (you have to code it yourself and use some sort of cron) but something tells me that AWS is working hard to fix that. And that’s really another thing we love in AWS. Like us they constantly improve their services and this turns them into a great partner.</p><p>You’ll never reach perfection but you can get closer and closer.</p><p><strong>The final result</strong></p><p>At the end of the day, allowing our engineering team to focus on the real-time data sync features, DynamoDB has been proving a spot-on choice, enabling our clients to write elegant and easy-to-read code like this (a JavaScript client reacting to an item update performed by another user):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1693204f6804979ce7390df2272ee3/href">https://medium.com/media/3f1693204f6804979ce7390df2272ee3/href</a></iframe><p>If you’re looking for a managed hosted NoSQL cloud database that scales, Amazon’s DynamoDB might be the best option for you at the moment. If you also need real-time data-sync features to keep your users synchronized, DynamoDB can’t do much for you there, but Realtime Cloud Storage can. You’ll have all the benefits of DynamoDB along with super-sleek real-time database triggers that will make your app almost write itself.</p><p>But don’t take my word for it, go to <a href="http://framework.realtime.co/storage">http://framework.realtime.co/storage</a> get your free license and take Realtime Cloud Storage for a spin.</p><p>Let me know your findings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=749ffdc957a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>