<?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 Pritam Roy on Medium]]></title>
        <description><![CDATA[Stories by Pritam Roy on Medium]]></description>
        <link>https://medium.com/@roypritam1234?source=rss-7a6b426a25b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*u-TUHhCUCYsCVa1QZkgdCQ.png</url>
            <title>Stories by Pritam Roy on Medium</title>
            <link>https://medium.com/@roypritam1234?source=rss-7a6b426a25b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:58:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@roypritam1234/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[Bancor Liquidity pool interactions with Katanapools]]></title>
            <link>https://medium.com/@roypritam1234/bancor-liquidity-pool-interactions-with-katanapools-c9ae4acd9fd7?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9ae4acd9fd7</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[liquidity-pool]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[bancor]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Sun, 17 May 2020 10:49:08 GMT</pubDate>
            <atom:updated>2020-05-17T11:22:30.117Z</atom:updated>
            <content:encoded><![CDATA[<h4>Katanapools lets you enter any liquidity pool and earn pool rewards either with all reserves or any one of the reserves in the pool</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*8zhssa3Rxv1cd269.png" /></figure><p>Katanapools allows you to create liquidity pools, fund and liquidate existing pools via a flexible UI solution suitable to intermediate and advanced crypto investors. Through the <a href="https://katanapools.com/pool/view">view-pool</a> interface, you can view pool details, your pool reserve token holdings, set allowance for the pool converter and Bancor network contract as well as fund any liquidity pool provided you have at-least one of the reserves of the pool. You can also liquidate your pool holdings into all of the reserves or any one of the reserves.<br>It is now possible to enter a pool using a single reserve, if the user chooses this option, the tokens are swapped in-place to create the ratio of reserves required to enter the pool.</p><p><strong>You can interact with any Bancor liquidity pool via </strong><a href="https://katanapools.com/pool/view"><strong>https://katanapools.com/pool/view</strong></a> <strong>You can also create new Liquidity pools with arbitrary ERC20 tokens in arbitrary reserve ratio via </strong><a href="https://katanapools.com/pool/create"><strong>https://katanapools.com/pool/create</strong></a></p><h3>Setting Approval and Allowances</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*ygytjFCXoWhV8gXYED5X8w.png" /></figure><h4>Approval for PoolConverter contract</h4><p>Funding a liquidity pool usually requires n + 1 transactions where n is the number of reserves in the pool because each reserve needs to be approved before a fund transaction can be made.<br>Additionally if there is already a previous allowance has been made which is &gt; 0 but &lt; allowance required for current transaction, then the allowance needs to be reset via calling approve(0) function. This makes the required number of transactions 2 * n + 1 for all practical cases.</p><p>This can be reduced to just 1 transaction is a high allowance is provided to the pool converter function for all of the reserves. This makes repeated funding much faster and also saves on gas costs. Katanapools thus allows the user of a wallet to approve a high amount for all of the pool reserves to the pool converter making funding using all reserves a single click process.</p><h4>Approval for BancorNetwork contract</h4><p>Additionally if the user wants to fund a pool using just 1 reserve (pool zap) they need to perform further 2* (n — 1) transactions in addition to the transactions mentioned in the previous section to convert the selected reserve to the pool reserves in the ratio needed for pool funding. This can be reduced to (n — 1) transactions if a high approval is provided for all the pool reserves for the BancorNetwork contract which is used for pool swaps. Thus the trading interface also allows the user to approve the BancorNetwork contract for all pool reserves.</p><p>All approvals can be revoked by the user at any time using the revoke functionality in the approvals section.</p><p><strong>Thus by providing approvals to both the pool converter and bancor network contract the number of transactions needed for single token pool funding (zap) is reduced from 4 * n to just n transactions where n is the number of reserves in the pool.</strong></p><h3>Funding and liquidations</h3><p>You can fund a liquidity pool using all of the reserve tokens or you can zap into a liquidity pool using any one of the reserves.</p><p><strong>The zap process is entirely controlled from the user wallet and is more effective than zap mechanisms which require the user to transfer the funds to a third party contract as in Katanapools zap any balance from the conversion is left in the user wallet.</strong></p><p>Here are the different funding and liquidation mechanisms through which a user can enter or exit a Bancor liquidity pool.</p><h3>Fund pool tokens using all pool reserves</h3><p>The traditional method of funding pool tokens is still the most efficient one, in order to fund the pool just enter the number of pool tokens you desire and the app calculates the number of reserve tokens you would need to stake in order to obtain the desired number of pool tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*-z8gyAnuMFYB3SHwCS1d5Q.png" /></figure><p>The transactions required in this method of pool funding are</p><ul><li>Approvals for all pool reserves to the Pool converter for the amount needed to mint the desired number of pool tokens as shown above.</li><li>Calling the fund function of the pool converter.</li></ul><p>After the transactions have completed the reserve tokens will be transferred to the pool and the newly minted pool tokens will be transferred to your wallet.</p><h3>Fund pool tokens using any one of the pool reserves</h3><p>With a large number of recently created pools which have an arbitrary number of reserves, there is a growing need for a mechanism that lets users to fund pools without requiring them to have all of the reserves. Single reserve funding (Zap) does just that. It allows the user to specify which reserve they would like to use to fund the pool and the amount of pool tokens they desire and calculates the amount of reserves needed to create the reserve array in the ratio required to mint the required number of pool tokens.<br>When the user confirms the app calls BancorNetwork contract to smartly create the reserve array in-place using the best path for swaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*6Jar-XADcOYKeD_ZvJhp3w.png" /></figure><p>The main advantage for the community is that the liquidity never leaves Bancor as it uses either the same or different Bancor pools to create each of the swaps.</p><p>The main advantage for the user is that they do not need to trust a third party contract. All the transactions are initiated from the user wallet and any balance from the swaps is left in the user wallet rather than being deposit into a third party contract.</p><p>The transactions that will be needed for funding a pool with a single reserve are</p><ol><li>n — 1 Approvals for approving token swaps from chosen token to other reserve tokens (Not needed if BancorNetwork contract was previously approved as in section 1)</li><li>n — 1 Transfers for token swaps for chosen token to other reserves.</li><li>n approvals for approving token transfer from user wallet to Bancor converter contract. (Not needed if Converter contract was previously approved as in section 1)</li><li>1 Fund transaction to mint the pool tokens and transfer to user wallet.</li></ol><h4>Liquidate pool holdings to all pool reserves</h4><p>You can liquidate your pool holdings to all pool reserves, just enter the number of pool tokens you would like to withdraw and the app will calculate the amount of reserve tokens you would receive after the transaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*tEevOz4kIcVvCAQt.png" /></figure><p>The pool liquidate event to all reserve tokens will encompass the following transactions-</p><ul><li>Approve converter to provide the necessary pool token allowance.</li><li>Call the liquidate function to liquidate the pool tokens into pool reserve tokens according to the Bancor formula.</li></ul><h4>Liquidate pool holdings to one of the pool reserves</h4><p>You can also liquidate your pool holding to any one of the pool reserves. When you withdraw to a single reserve the app will call the pool liquidate function and thereafter the reserves will be converted to the chosen token using the best path approach.</p><p>Amount of pool token to withdraw (Make sure you have enough pool tokens to cover the amount you wish to withdraw)<br>Click on calculate, this will show the amount of chosen tokens you will receive after the conversion has been completed.</p><p>Click withdraw and sign the subsequent transactions.</p><p>The following transactions will be a part of pool withdraw-</p><ul><li>Approve pool token liquidate.</li><li>Liquidate pool token.</li><li>For each of the reserves other than the chosen reserve-<br> -Approve transfer from reserve to chosen reserve token (Will be skipped if you have approved BancorNetwork contract previously and provided the necessary allowance)<br> -Transfer from pool reserve to the chosen reserve.</li></ul><p>Be sure to checkout out Katanapools for swapping tokens, creating pools and interacting with pool tokens at <a href="https://katanapools.com/">https://katanapools.com/</a></p><p>For more information regarding creating and funding liquidity pools on Bancor head over to Bancor docs <a href="https://docs.bancor.network/">https://docs.bancor.network/</a></p><p><em>Originally published at </em><a href="https://tenminstech.com/fund-bancor-liquidity-pools-with-any-one-reserve/"><em>https://tenminstech.com</em></a><em> on May 17, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9ae4acd9fd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless application architecture with GraphQL]]></title>
            <link>https://medium.com/@roypritam1234/serverless-application-architecture-with-graphql-b784205d4106?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b784205d4106</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Wed, 07 Aug 2019 13:06:54 GMT</pubDate>
            <atom:updated>2019-08-08T13:47:50.792Z</atom:updated>
            <content:encoded><![CDATA[<h4>Illustrating the advantages of GraphQL over REST and demonstrating how GraphQL enables supercharged serverless applications which are faster and more performant than REST API counterparts</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FuomE2w4TXe4%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DuomE2w4TXe4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FuomE2w4TXe4%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/61e932cb1b676214522cff8aff250e5a/href">https://medium.com/media/61e932cb1b676214522cff8aff250e5a/href</a></iframe><p>GraphQL is a query language that lets you create powerful interactions with minimal to no middleware logic by allowing clients to query for and update exactly what they need and render views accordingly. This allows you the developer, the creative and technical freedom to focus on your application logic without having to worry about the underlying network and compute costs of your code. This is particularly useful for mobile-first applications where bandwidth and computing power is constrained and devices need to render complex views with the logic being executed entirely on the client side.</p><p>This is a paradigm shift from the traditional REST based architectures where clients were constrained by predefined endpoints and often required over-fetching and under-fetching of data and additional expensive map and filter compute on the client-side to normalize the response data according to the views.</p><h3>Advantages of GraphQL over REST</h3><p>To understand how GraphQL shines, we need to first understand some of the limitations of REST.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*VewGG8Q0s6BeBxcEF17zPw.png" /></figure><p>A typical REST API server allows for definition of various endpoints of type GET, POST, PUT, etc. each of which is suitable for a particular task and for each new task the developer would either define a new endpoint or combine the results from existing endpoints on the client to accomplish the task.</p><p>A REST server can thus be visualized as a vending machine, where each button accomplishes a particular task, if you wanted to add a new functionality you’d add a button for that task. <br>GraphQL, on the other hand allows for complex querying and updates without needing to add extra endpoints for each such operation, for instance you can ask for specific fields for an object, paginate lists based on custom criteria or define resolver functions which allow you to construct queries as exactly how your view renders the data without needing to add extra endpoints or doing additional compute on the client.</p><p>The primary advantages of GraphQL over REST are as follows-</p><h4>Querying multiple types at once:</h4><p>With a classic REST architecture, if you wanted to query multiple types of objects at once, you either create new endpoints for each custom view or you send multiple requests from the client to fetch the different objects/lists and do client side JOINs and filter out the required keys. This approach is not only inflexible and verbose and also compute and networks intensive as it returns more data than is needed and requires client side computations.</p><p>With GraphQL however you can create indexes to query lists of a given type and resolvers to query custom lists consisting of many indexes. This allows you to construct queries that can match many different views and combine fetching multiple types of objects in a single query.</p><h4>Querying for only what you need:</h4><p>In a REST based application when creating custom listings, such as paginated views on criterion such as items created after a certain date, or below a certain price, you typically need to fetch all items and then do a client side filter before doing a render. This leads to either a mushrooming of custom endpoints each supporting a view or expensive data over-fetching, once more putting network and compute constraints on the client. <br>With graphQL you can construct your query to fetch only the page that the client needs and request only the keys that the view needs. This saves the overhead of doing client-side filtering or having to create custom endpoints to support every different types of query that a view requires.</p><p>In a REST server you create new data or edit existing data, you typically create separate endpoints for single vs. bulk create/updates and also pass down the entire objects to the middleware and let the server find the diff of the objects. This leads to wasted bandwidth as more data is sent than is needed as well as additional compute on the server slowing down the application responsiveness.</p><p>GraphQL allow you to define custom <a href="https://graphql.org/learn/queries/">mutations</a>, which are basically definitions by which you can tell your database exactly which fields you want to modify, and thus saves you the overhead of having to send down entire objects. Since you can fetch data exactly customized to your applications, you no longer need to do expensive middleware logic.</p><h4>Model your application logic as an object graph instead of relations</h4><p>Some applications such as social-networking applications are naturally modeled as object graphs instead of relationships between tables. In a traditional REST architecture, the API layer translates the relational data model consisting of rows and columns into the object model that the UI expects. With a GraphQL, you can model your data as an object graph just as is expected in the client. This lets you simplify your application logic and model the application bottom-up as an object graph. It is no accident therefore that the initial implementation of GraphQL was developed by Facebook to solve the problem of building a performant mobile app for their social network application.</p><h3>Comparing a typical RESTful architecture with graphQL/Serverless architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2tl_VDRf38C1D5zo.png" /></figure><p>In a typical 3-tier RESTful architecture, we have a client layer running on user devices. The client is typically running javascript on a browser and the UI is modeled as an object-graph consisting of documents. The second layer is the API server which is responsible for understanding the UI queries and transferring them to the data layer. For each client query type there is an endpoint, and the client creates more complex views by combining the results of multiple queries to different endpoints.<br>This layer is defined by the REST specification and exposes endpoints of different types such as get, post, put etc. The third layer is the data layer which is typically a relational database consisting of tables which in turn of rows and columns.</p><p>Serverless architecture with graphQL enables removing the API indirection layer altogether and allows the client to send graphQL queries and mutations directly to the database graphQL endpoint.<br>While serverless architectures can be REST based as well, such architectures usually involve a REST API gateway which intercept and route the client requests to the managed data-layer and are not as beneficial or ground-breaking, the true potential of serverless is exposed with native graphQL support.<br>Such an architecture skips the REST api layer altogether and uses the data-layer itself as a thin API which the client can talk to.<br>Furthermore the data-layer in serverless architecture is usually highly available and globally replicated, allowing for low latency response to clients connecting from around the world. Native graphQL support by managed database services such as FaunaDB are enabling the new paradigm of serverless application development.</p><h3>Advantages of GraphQL/serverless apps over RESTful apps</h3><p>GraphQL based serverless architecture provides many advantages over RESTFul apps such as removing the need to run dedicated API servers and saving the costs associated with developing and deploying them. API servers are a layer of indirection which slow down the application responsiveness unless globally replicated themselves. Furthermore they also expose security loopholes unless the endpoints are properly secured. Without the need to run API servers, and using managed multi-tenant database layer, you can simplify your application orchestration and maintenance and can focus on your core business logic running in lean and agile mode. This not only results in huge-cost saving as using managed multi-tenant database means that you only pay for what you use and can potentially scale infinitely but also reduce the surface of attack on your application.</p><p>Any app of moderate complexity running on a RESTful architecture soon sees a myriad of endpoints which can easily turn into a maintenance nightmare without accurate documentation, this leads to significant technical debt on the part of the organization and with each app upgrade APIs need to be versioned and are often not compatible with previous versions.</p><p>When the application is using graphQL, it means that the client needs to run less computations since it can ask for and send exactly the objects and keys that it needs to. This allows developers to add more features without worrying about device compute constraints and allows for rich applications to run on smaller devices. Furthermore since the client and the API are exchanging only the minimum required amount of data, it also leads to network cost savings for the client since less bandwidth is utilized and compute costs for the server since it needs to process less data.</p><p>Since managed database services like FaunaDB which natively support GraphQL code execution run in a CDN like database-as-a-service model, the app has access to a pay-per-use globally distributed, fast data-store without needing to orchestrate containers itself and can service clients with extremely low latency and high throughput.</p><h3>Conclusion</h3><p>In this post, we saw how GraphQL is changing the landscape of application development though a superior and more flexible CRUD schema, allowing us to implement operations such that they exactly model our views and also allowing us to perform operations directly on the database without needing an API layer or additional logic for translating our object model to and from a relational schema. Not only is this is more efficient compute and less round trips but we have managed to entirely remove a layer of indirection from our application architecture. So go forth and build your next app with GraphQL there are several excellent resources available online to help you get started and many of the major public API endpoints now support GraphQL as a first-class citizen.</p><p><em>Originally published at </em><a href="https://tenminstech.com/graphql-serverless-architecture/"><em>https://tenminstech.com</em></a><em> on August 7, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b784205d4106" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decentralized Finance (DeFi) stack built on Ethereum]]></title>
            <link>https://medium.com/@roypritam1234/decentralized-finance-defi-stack-built-on-ethereum-feea8f93a47d?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/feea8f93a47d</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Mon, 05 Aug 2019 12:48:30 GMT</pubDate>
            <atom:updated>2019-08-09T13:45:30.727Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deconstructing the Ethereum DeFi stack</h3><h4>A suite of permissionless, open applications and infrastructure that seeks to revolutionize and replace finance as we know it.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Ft4TlfrcmlB0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dt4TlfrcmlB0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Ft4TlfrcmlB0%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/dbdda73bb24ab66c79555b88e969c4a1/href">https://medium.com/media/dbdda73bb24ab66c79555b88e969c4a1/href</a></iframe><p>Software has been chipping away at the walled castles of finance for a while now…but over the past couple of years a set of protocols and products built on top of the blockchain have emerged that threatens to disrupt the sector entirely. Decentralized finance or DeFi as it has come to be known promises to usher in an era of transparent and secure financial services which can potentially bank the unbanked, eliminate high level corruption and flip our existing models of sectors ranging from banking and exchange to insurance entirely on it’s head.</p><p>DeFi is not a single product or company but is instead a set of products and services that together compose stacks which can act as a replacement for institutions ranging from banking, insurance, bonds and money markets. Let’s take a look at the products that create this stack and weigh the pro’s and cons of traditional systems vs. their decentralized equivalents.</p><p>Currently, even with its limited applications, an equivalent of 600 million USD is locked into decentralized finance applications and the number is only set to grow in the future.</p><h3>Replacing traditional financial models with composable stacks built with smart contracts-</h3><p>To understand how decentralized products will replace centralized entities we need to first understand the abstractions the centralized financial systems of today represent. A bank is essentially an entity which you lend your money to and give them for safekeeping. In turn the bank gives you a rate of interest compounded annually. The bank in turn lends the money to borrowers at a higher interest rate. Banks also act as an intermediary that lets you convert assets of one class to another. All of these services can be automated with immutable contracts on the blockchain removing the need for such an intermediary. Let us take a deep-dive and explain how the pieces fall into place to construct this jigsaw puzzle.</p><p>Ethereum is the base layer not only as the EVM which run the code for the smart contracts used by the layers above, but also as a with the Eth2.0 upgrade, holders can stake their tokens and earn interest in the base layer proportional to amount and time that they have staked their tokens, just like bond markets are the backbone of the FIAT economy [9] Ethereum staking will be the backbone of such a DeFi infrastructure.</p><p>Check out <a href="https://medium.com/@TrustlessState/ethereum-the-digital-finance-stack-4ba988c6c14b">this article</a> by <a href="https://twitter.com/TrustlessState">David Hoffman</a> for a detailed explanation of the equivalence between Ethereum base layer and global bond markets.</p><blockquote><em>In Ethereum 2.0, the functions of the centralized government and its federal reserve have been consolidated into the code of protocol. The fixed, predetermined </em><a href="https://docs.ethhub.io/ethereum-roadmap/ethereum-2.0/eth-2.0-economics/#staking-rewards"><em>staking rate in Ethereum 2.0</em></a><em> solves the issue of a central party from printing money. — </em><a href="https://twitter.com/TrustlessState"><em>David Hoffman</em></a><em>, Ethereum: The Digital Finance Stack</em></blockquote><h3>Lending and borrowing-</h3><p>Over the past couple of years many services have emerged which allow you to lend your assets and earn an interest or borrow assets for margin trading/arbitrage etc. the primary disadvantage of current systems is that since there are no mature reputation systems, loans can be accessed only via over-collateralizing i.e. in order to borrow another asset (typically a stable-coin) you will typically need to put 150% value collateral and at the end of the maturity period once you pay back the loan, you get back your collateral minus interest that is owed. Regardless of this disadvantage, it is still appealing, if the borrower believe that the price of the collateralized asset will go up over time and doesn’t want to sell the underlying asset. Also selling the asset generates a taxable event in most jurisdictions while using a CDP to borrow a stable coin against Ether provides them with liquidity without generating a taxable event.</p><p>Some of the biggest lend/borrow markets currently in the ecosystem are-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x0lZHFqWE5ocSLpw.png" /></figure><p><strong>Dharma</strong>- <br><a href="https://www.dharma.io/">Dharma</a> is a direct matching peer-to-peer lending platform i.e. users can lend their tokens but must wait for their orders to be matched. Interest rates are determined through a non-transparent black-box process. Users can borrow supported assets for a 90 day period and can pay it back at any time by paying the interest for the entire duration of 90 days.</p><p><strong>Compound-</strong><br>Compound is a protocol that creates algorithmic money markets. It uses an intermediary token known as cToken to the token being lent and interest is accrued and paid off in the cToken upon each block creation. The interest rates are calculated based on market dynamics, for eg. if there is more demand for loans than there are lenders, lenders would get higher interest rates and vice-versa.</p><p><strong>Maker -</strong><br>Maker allows users to mint the Dai stable-coin against a collateral paid in crypto. So if a user wanted to mint the Dai stablecoin that would have to put a collateral in crypto in the Maker CDP and upon maturity they can pay back the stable-coin along with a stability fee to retrieve their asset.</p><h3>Asset backed stable-coins-</h3><p>Stable-coins are tokens whose value remains stable with respect to FIAT over time. This is achieved via algorithmic collateral placed either in FIAT (USDC, Paxos etc.) or in Crypto (Dai). Stable-coins form a vital part of the ecosystem, since it allows users to use it as a base currency equivalent to Fiat while staying in crypto and additionally not generating a taxable event for transfers and exchanges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*INSyd0W4BJUQtywT.png" /></figure><p><strong>Dai- </strong><br>Dai, generated through Maker is currently the biggest stablecoin by volume and the value is held stable against the USD through a stability fee mechanism which is charged from the borrowers when they mint new Dai by collateralizing their Ethereum assets.</p><p><strong>USDC- </strong><br>USD Coin by Coinbase is a Fiat backed stable coin, meaning that the collateral responsible for keeping the value stable is placed in USD.</p><p><strong>Paxos-</strong><br>Paxos is another USD backed ERC20 compliant stable-coin which is unique in that it is regulated and approved by the New York State Department of Financial Services. Recently they also <a href="https://www.coindesk.com/paxos-to-issue-up-to-100-million-of-stablecoins-on-ontology-blockchain">announced</a> a decision to mint up-to 100 million USD worth of stable-coins on the Ontology chain.</p><h3>Derivatives, peer-to-peer margin and prediction markets-</h3><p>Smart contracts also allow applications like insurance on crypto assets, second or third order derivative markets for real world events, and peer-to-peer margin trading and leverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gBXLpEd-Tw4PZmdq.png" /></figure><p><strong>Augur- </strong><br>Augur is a prediction market which allows users to stake tokens and bet for or against future outcomes of real-world events. Such markets are still in their infancy buy with enough users can also serve as accurate predictions for the outcome of future events.</p><p><strong>CDx- </strong><br>CDx aims to provide the crypto version of a deposit insurance. It also provides crowd-sourced transparency about exchange security and default risk by allowing users to bet against exchanges which are likely to get hacked.</p><p><strong>dYdX-</strong><br>dYdX is a protocol that provides margin trading and leverage opportunities in a decentralized peer-to-peer manner. It allows traders to short or long an ERC20 token without having to sell the underlying asset.</p><h3>Decentralized Exchanges-</h3><p>Decentralized exchanges form a vital part of the DeFi ecosystem, as they allow users to exchange assets without requiring to transfer custody of their assets to a third party. Decentralized exchanges can be categorized as either having order-books, settlement and liquidity either on-chain or off-chain. [3] Let’s take a look at some of the biggest decentralized exchanges and protocols out there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WSsXst2kM8M5QX8c.png" /></figure><p><strong>0x protocol- </strong><br>ox protocol is set of libraries that allows peer-to-peer to trading and transfer of assets. It uses on-chain settlement with off-chain order-books and pooled liquidity. This method allows trades to be decentralized without needing any intermediary while also allowing sufficient liquidity and transaction throughput without clogging the Ethereum network. There are currently multiple decentralized exchanges built on top of 0x protocol each of which can theoretically share liquidity and access price discovery mechanisms etc.</p><p><strong>Kyber-</strong><br>Kyber network is a swapping mechanism for exchanging ERC20 tokens and uses on-chain settlement and on-chain pooled liquidity. All swaps are transparent and peer-to-peer without needing a trusted third-party or intermediary of any sort. KNC is Kyber network’s token which is used to pay fees for each transaction.</p><p><strong>Bancor-</strong><br>Bancor allows for peer-to-peer swapping of supported assets and is unique because it also supports some non ERC20 tokens such as EOS to be swapped for regular ERC20 assets. It uses on-chain settlement of swaps along with on-chain pooled liquidity.</p><h3>Advantages over traditional financial equivalents-</h3><ol><li><strong>Full custody of capital-</strong><br>When you deposit deposit your money in a bank or a centralized exchange, you lose custody of your assets and are exposed to high levels of counter-party risk. With fully decentralized services all transactions are executed from your wallet and you do not lose custody of your assets at any given point of time.</li><li><strong>Security and transparency-</strong><br>With fully decentralized platforms all transactions are recorded on the public ledger and open to software audit by any interested party, contrast that with centralized exchanges and financial institutions which operate in a black-box environment and thus have an incentive to cheat.</li><li><strong>Higher annual rate of returns than comparable FIAT bond schemes-</strong><br>The Fed policy rate offers interests at 2–3% APR on government bonds. Collateralized stable-coins however offer higher interest rates and APRs along with advantages such as greater transparency and services which are easier to access.</li><li><strong>Increased capital access-</strong><br>Much of the world, particularly the poor and the unbanked and those living in countries run by authoritarian regimes or ones hit by sanctions do not have access to liquidity or capital in the form of USD. They are thus left out of the global prosperity. Decentralized services can bring capital access to these masses since these are not censorable and there are typically no location requirements to sign-up for these services.</li></ol><h3>Risks and limitations-</h3><h3>1. Overcollateralization-</h3><p>Perhaps the biggest limitation of current DeFi systems is the lack of a credible reputation/credit system. As such most loans must be taken out against Overcollateralized crypto assets. This is not appealing to many traders since they would rather not collateralize on a peer-to-peer platform. This does not help the unbanked since without a crypto collateral which in turn requires a Fiat gateway, they cannot access liquid capital.</p><h3>2. Technological risks-</h3><p>There are several general technical as well as blockchain specific risks, for instance -<br><strong>Smart-Contract code bugs and Software errors-</strong><br>There have been several high-profile bugs and exploits found in DApp code in the recent years and such bugs are notoriously hard to fix and in the worst case may even cause the chain to split and become unstable. In financial applications in the absence of exhaustive and thorough code-audit of the smart contracts, may cause the entire stack to topple like dominoes and cause significant losses to investors.</p><p><strong>Network congestion and transaction fees on the blockchain-</strong><br>One of the biggest limitations of applications running on the blockchain is that because of the way blockchains work, they can only commit a limited number of transactions per second, compared to centralized providers. This is an active topic of research and is popularly known as <a href="https://bitcoinist.com/breaking-down-the-scalability-trilemma/">the scalability trilemma</a>. As such doing every operation on-chain would be slow and expensive. Several second layer solutions have been developed or in works to overcome this including DeXes using off-chain orderbooks and only broadcasting orders when finalized and other solutions are being actively researched and implemented.</p><h3>3. Competing blockchains and protocols-</h3><p>Several established blockchains such as EOS and Oncology as well as newer blockchains and protocols such as Cosmos and Polkadot are rushing to kickstart DeFi ecosystems on their own platforms, this may pull some developers and liquidity away from Ethereum based DeFi systems. <br>However healthy competition and increased interest just goes on to demonstrate the potential and use-cases of the ecosystem and only adds value. Furthermore many of the applications are being designed in such a way that they are interoperable with the Ethereum based ecosystem.</p><h3>Future prospects-</h3><p>Regardless of where you stand on the spectrum of whether tokenization of assets and services is a good roadmap for mankind, it is easy to agree that a world where commodities, goods and services are tokenized and the need to a trusted third party intermediary is removed will be much more efficient and transparent than the systems of today.<br>In a hyper-tokenization scenario, blockchain based peer-to-peer protocols have eliminated the need for institutions that exist today solely because of the need for trust and verifiability between parties executing a transaction. <br>In the near future, when some of the promising projects come to fruition you can potentially access credit on the the blockchain with reputation systems, buy and sell tokenized stocks versions of stocks and futures such as S&amp;P and commodity markets ( <a href="https://umaproject.org/">UMA Protocol</a>), predict outcomes of future events with a surprising degree of accuracy ( <a href="https://www.augur.net/">Augur</a>) and witness hundreds of millions of people being lifted out of poverty as they get access to capital, start businesses and get education without needing a bank account or paper documents.</p><h3>Conclusion-</h3><p>The great driving force behind this movement is it’s transparency. Since the code is open and allows anyone to contribute, it incentivizes individuals and teams to create products to provide solutions and address the shortcomings and potentially build a businesses around them. <br>Although the ecosystem is still in it’s infancy but there is great promise and development to address the shortcomings and each potential disadvantage is seens.<br>This is of-course not an exhaustive list of apps and frameworks that comprise the DeFi ecosystem, nor are these the only products targeting their particular niche but merely used to illustrate the composition and functionality of the parts of the stack. For a more exhaustive list visit <a href="https://tenminstech.com/eth-defi-stack/defi.network">DeFi network</a>.</p><h3>References and Further reading-</h3><p>According to a World bank report released in 2018, 1.7 billion people across the world are unbanked.</p><ol><li><a href="https://defi.network/">DeFi Network portal</a></li><li><a href="https://defiweekly.substack.com/">DeFi weekly newsletter</a></li><li><a href="https://www.delphidigital.io/defi">Decentralized Finance: Thematic insights</a></li><li><a href="https://info.binance.com/en/research/marketresearch/defi-1.html">Binance research: Decentralized Cryptoasset lending and borrowing</a></li><li><a href="https://hackernoon.com/how-decentralized-is-defi-a-framework-for-classifying-lending-protocols-90981f2c007f">How Decentralized is DeFi? A Framework for Classifying Lending Protocols</a></li><li><a href="https://medium.com/macro-narratives-in-blockchain/the-next-fintech-global-open-finance-infrastructure-90ac093a411b">The next FinTech: Global “Open Finance” Infrastructure</a></li><li><a href="https://www.bitrates.com/news/p/decentralized-finance-defi-a-quick-walkthrough-of-the-ethereum-defi-stack">Decentralized Finance (#DeFi): A Quick Walkthrough of the Ethereum DeFi Stack</a></li><li><a href="https://satoshiand.co/defi-expectations-game-changer-for-modern-finance/">DeFi Expectations: Game-changer For Modern Finance</a></li><li><a href="https://medium.com/@TrustlessState/ethereum-the-digital-finance-stack-4ba988c6c14b">Ethereum: The Digital Finance Stack</a></li><li><a href="https://ethereumworldnews.com/ethereum-defi-milestone-eth-falls-bitcoin/">Ethereum DeFi products Hit Milestone as ETH falls against Bitcoin</a></li></ol><p><em>Originally published at </em><a href="https://tenminstech.com/eth-defi-stack/"><em>https://tenminstech.com</em></a><em> on August 5, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feea8f93a47d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Problem-Solving with Shopify Admin API — GraphQL vs REST]]></title>
            <link>https://medium.com/kashmerelabs/problem-solving-with-shopify-admin-api-graphql-vs-rest-b5239a67e7f2?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5239a67e7f2</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[shopify-development]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 15:48:30 GMT</pubDate>
            <atom:updated>2019-01-24T15:48:30.418Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem-Solving with Shopify Admin API — GraphQL vs REST</h3><h4>Shopify supports GraphQL and REST based integrations for custom app development. Let’s unravel some use-cases for GraphQL and REST so we can make better choices while designing our app without having to make costly code changes further down the lifecycle</h4><h3>GraphQL in context</h3><p>In a typical app-dev scenario, where you are the one building the API and the client, you can design your endpoints exactly tailored to functionality that your client exposes… but when developing clients for third-party platforms like Shopify, the API endpoints exposed to you as an app-developer tend to be generic and your client may need more or fewer data points than what the API exposes. This leads to inefficiencies and wasteful chaining.</p><p>GraphQL is designed to solve some of the inefficiencies of REST related to data over fetching and under fetching by minimizing the data that needs to be transferred over the network.<br><strong>In a nutshell, the motto of GraphQL is don’t waste bandwidth and don’t fetch more data than you need…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*odaQWYEB4z-epp13o4sJ7A.png" /></figure><p>GraphQL is the sniper rifle of data operations and anyone who has used one or has played ghost warrior will tell you that sniper rifles do serve a purpose but sometimes what you need is a chaingun. So let’s examine some use-cases in Shopify admin and efficiency of GraphQL vis-a-vis REST and requests where each is suitable.</p><h3>Comparing efficiency and costs —</h3><p>GraphQL provides you with constructs to reduce the round-trips and chaining for some requests. It is however not just the speed that you can optimize for, Rate-limits work differently in GraphQL and REST API. While rate limits in Admin API are tied to the number of requests you make in a given time-period, rate-limits in Shopify GraphQL are tied to the costs of each request that you make and governed by the Leaky-bucket algorithm, so by optimizing for the kind of request you can potentially make more requests without hitting individual rate limits. To see how rate limits work in GraphQL check out this documentation link here.</p><p>For instance, a request to <strong>duplicate a product</strong> in REST would be a two-step operation.</p><ol><li>Fetch the product to be duplicated.<br>Edit the fields to be updated.</li><li>Post the new product description.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22be71a79f44a909d263f35ec0c17be1/href">https://medium.com/media/22be71a79f44a909d263f35ec0c17be1/href</a></iframe><p>In GraphQL it would instead be a single step operation using the DuplicateProduct mutation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eb9d74187832f4a03a6c47f0303829e/href">https://medium.com/media/4eb9d74187832f4a03a6c47f0303829e/href</a></iframe><p>As is evident, for most chained request queries, a GraphQL equivalent will reduce the number of roundtrips and save network bandwidth and unlike the REST equivalent will not hit API limits.</p><h4>So where does it make sense to use the REST API instead?</h4><p>In a situation where a single atomic REST request can be used to achieve the desired functionality, such as in bulk query/update operations, fetch count operations, that operate on the entire set and no delimiter or cursor needs to be specified.</p><p>For instance, a query to <strong>get all products in a store</strong> would require only one REST call without needing any knowledge of the exact number of products in the store, whereas the GraphQL implementation would require you to get n products and then loop over the cursor until you get to the end of the list. The alternative would be to pick an upper estimate of products which would reserve a bigger bucket cost than what you need, and estimating an upper-bound that is too high may hamper your ability to make further queries in quick succession.</p><p>Shopify supports a simple REST endpoint that allows you to fetch all products in the store without needing to know the number of products beforehand.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e444f6260061263f61cc7e56ab52b02/href">https://medium.com/media/1e444f6260061263f61cc7e56ab52b02/href</a></iframe><p>The graph API equivalent requires you to either fetch first n products and then iterate over the cursor until you reach the end or alternatively estimate an upper bound of products n and fetch the first n products. For instance, if you knew that the number of products in your store is less than an upper bound N, you could use the following query to fetch all the products in your store.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0402c5d1f82821b454dad472a70aa56/href">https://medium.com/media/c0402c5d1f82821b454dad472a70aa56/href</a></iframe><p>The problem with this approach is that you reserve a bucket capacity of n (900 in this case) even though the actual number of products may be less than 900. This hinders your ability to make future GraphQL requests until the current request returns and the extra allocated space is released.</p><h3>Better choices made earlier makes you more productive</h3><p>When designing a new app, we usually work on an exploratory approach, we try something if it doesn’t work we try something else. The problem with rate-limits and scalability of queries, however, is that they often don’t manifest until you have shipped and start seeing a growing number of users. Then fixing scalability bugs becomes more like debugging a space-shuttle mid-flight. Some general guidelines when designing an application query layer —</p><ol><li>If you want to fetch all items of a type and the server provides an endpoint that supports it, it’s better to use the REST endpoint than page through Graphql cursors.</li><li>If there is a straightforward endpoint that allows you to achieve the desired outcome use REST.</li><li>If you find yourself chaining a bunch of requests, it may be better to design a GraphQL solution.</li><li>If the app is targeted towards bandwidth-constrained users such as those using phones and smart-watches, you should design GraphQL solutions as reducing network round-trips is a feature that may make or break your app.</li></ol><p>The performance of GraphQL queries depends on several factors, not just how the query is constructed but also the GraphQL middleware is implemented. A GraphQL middleware which fetches from a graph database is likely to be more performant than one that does a join internally and exposes a graph API to the client.</p><p>GraphQL provides you with stronger constructs that natively allow you to query and mutate complex data types without chaining network requests. REST APIs provide standard solutions to the most common data queries and mutations. A performant app uses both REST and GraphQL in places where it shines and Shopify support for both standards means that apps can support complex use-cases and be fast at the same time by judiciously applying the two standards where they are needed the most.</p><p>If you found the above writeup useful, there are 50 ways (claps) to show your appreciation. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5239a67e7f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/kashmerelabs/problem-solving-with-shopify-admin-api-graphql-vs-rest-b5239a67e7f2">Problem-Solving with Shopify Admin API — GraphQL vs REST</a> was originally published in <a href="https://medium.com/kashmerelabs">KashmereLabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Experiences building a newsfeed out of twitter streams]]></title>
            <link>https://medium.com/hackernoon/experiences-building-a-newsfeed-out-of-twitter-streams-fdcaee7542d1?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdcaee7542d1</guid>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[build-twitter-newsfeed]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[twitter-newsfeed]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Mon, 27 Aug 2018 02:09:15 GMT</pubDate>
            <atom:updated>2019-04-23T09:38:49.578Z</atom:updated>
            <content:encoded><![CDATA[<h4>Modeling summarized views around topics on more than just popularity-indexes</h4><p>News spreads out of <a href="https://hackernoon.com/tagged/twitter">Twitter</a>.. faster than anywhere else…It’s amazing how much of the “breaking news” that we see or hear every day starts with a tweet. From <a href="https://twitter.com/elonmusk/status/1026872652290379776">tweets</a> which leave us questioning the nature of reality to twitter-politics all the way to crypto-twitter, what’s obvious is that Twitter is where it all starts.</p><p>Twitter feeds work great in a certain sense, we see tweets from people we follow and tweets liked by people we follow..but beyond the daily-active accounts most of us receive our news from link-shares or news media derived from tweets. There has been substantial effort across industries to create meaningful views of Twitter data-streams combining statistical classification models and other ML techniques to extract unique and interesting information.</p><p>At Snip, our writer recommendations engine runs a classification/clustering/topic-modeling pipeline to generate real-time news recommendations for writers. The current implementation extracts meaningful tweets and groups them into contextual clusters on a near real-time basis. It uses Logistic Regression for relevance classification and topic clusters are modeled via NMF with further extractive text summarization via weighting.</p><p>Through this post, I’ll outline some of the rationale and challenges in designing the system.</p><h3>Beyond Twitter search, filtering streams and contextual information from related entities</h3><p>The high-level technical architecture consists of an aggregator front-end and a <a href="https://hackernoon.com/tagged/machine-learning">Machine Learning</a> backend. The goal of the system is to provide a personalized twitter news feed to a user tailored to their interest with benchmarks and features based on the following metrics —</p><h4>Accuracy</h4><p>1. Combine Status and Timeline feeds and rank them in news-worthiness and accuracy.<br>2. Remove spam/marketing tweets from a topic feed. <br>3. Combine data from complementary sources and filter opinionated tweets to create an unbiased view of the event.</p><h4>Relevance</h4><p>1. The view should provide a chronological order of events as they happen and combine top and emerging events on the topic.<br>2. Vectorize tweets against news corpus to filter out news-tweets.<br>3. The system should not include inherent bias and result display should include discourse based on semantics and interactions alone.</p><h4>Quality</h4><p>1. News articles should be recent and up-to-date.<br>2. If news article has been redacted upstream, remove it from stream as soon as feasible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0VPRNnZG3PuW3WM3F2dFQ.png" /><figcaption><strong>Machine Learning Backend</strong></figcaption></figure><h3>Aggregating tweets around a topic</h3><p>Twitter provides us with three basic query endpoints, the search, timeline and the stream. Each gives a different view of a topic, and can we used to create interesting features. In order to create a near-complete view of the topic including semantic similarities (people and related entities) the basic structure should be for a topic which allows to get the maximum amount of data while being able to scale to hundreds of topics without hitting rate limits.</p><pre>[{“topic”: topicName, // Search topics<br>  “handles” : [], // Search timelines<br>  &quot;keywords&quot;: keywords, // Sample Realtime stream<br>}]</pre><p>Parsing and assigning contextual information to tweets, however presents unique challenges. A simple popularity based index often does not suffice for calculating the “news-worthiness” of an article, tweets are by default not news-articles, a deluge of automated accounts skew the results of any system trying to determine the newsworthiness and accuracy of an article based on popularity index and user-feedback alone.</p><h3>Relevance Classifier</h3><p>At the heart of this challenge lies a classification problem to filter bot-streams/opinionated tweets and user-posts from meaningful “newsworthy” texts. <br>This is to prevent the proverbial “garbage-in garbage-out” problem. The classified data can then be processed via clustering and topic-modeling pipelines to create a consumable views for news around a topic. A supervised learning approach works well with carefully chosen feature vectors.</p><h4>Model Training</h4><p>For our model training we have trained and tagged a corpus of few thousand tweets in each category on two metrics — SPAM and Relevance. This set will be used to train our models and validate the accuracy of the classifier for each category.</p><h4>Feature Vectors</h4><p>Feature vectors are combining text features, post metric features, combined with user-metrics and time-window for the tweet. For text features, we can combine TF-IDF vectors of lemmatized terms, with (1,2) n-grams and named entities.</p><p>Beyond the text processing though observation of tweets in a category we can identify semantics of spam tweets (such as containing terms like giveaway, rewards etc. or a large number of hashtags and mentions). We can build an additional index of spam features and pass it to the classification engine.</p><p>Additional features can be constructed via word2vec indexes of the tweets in a given category against a corpus of reliable news articles in the category to determine news-worthiness of the tweets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRuy-sM3u6npURykZWcwLQ.png" /></figure><h4>Model Generation</h4><p>We found that creating a general training model for classifying tweets across categories and topics often results in sacrificing accuracy.<br>On the flip side manually tagging training data for each individual topic is time-consuming and not very scalable, while resulting in higher accuracy of predictions. We built a supervised category-wise classification model by providing a feature set with high correlation with relevance and spam. Observation of a sample of tweets in a given topic/category corpus gives ideas for features which may be generalizable or specific to the given category.</p><p>The model is created via creating feature vectors from the labeled sample. The labelled corpus (around 1200 tweets) was divided into training and validation sets (0.33 * len(lebelled_set))<br>The feature vectors was created as described the the architecture diagram above. Features include a sparse TF-IDF vector, Doc2Vec similarity vector against a corpus of news articles on the topic and other language semantic features.</p><h4>Streaming Classification-</h4><p>Once the model is generated and pickled, we can use it to predict accuracy and spam classifications against a sample of tweets aggregated in real-time.<br>We can define an integer constant N or a timestamp T such that we can can filter a data frame to query against the last N tweets or inserted_at &gt; T.<br>We use Cassandra/Spark based distributed computing clusters to tokenize and label the tweets in near real-time and serve is via an API layer.</p><h3>Topic Modelling and Clustering</h3><p>Topic modeling can be done based on textual and cosine similarity with timestamp decay functions. The aim of the topic-modeling system is to group topics on semantic measures and not just text alone. For the topic modeling we benchmarked NMF, LDA and LSI algorithms. In an unsupervised setting, the results over NMF were most applicable over a wide range of topics. Aiming to keep the number of topics as relevant as possible, we start with an initial approximation that in a cleaned data-set, the number of topics = num_of_records / 10. We can further merge topics based on semantic similarity of divergence.</p><pre><br>num_topics = int(len(topic_frame)/10)</pre><pre>model = TopicModel(‘nmf’, n_topics=num_topics)</pre><pre>for topic_idx, top_terms in model.top_topic_terms(vectorizer.id_to_term, topics=-1, top_n=8, weights=True):<br>    // Top 8 Terms for each Topic, further filter by weights</pre><pre>for topic_idx, top_docs in model.top_topic_docs(doc_topic_matrix, topics=-1, top_n=6, weights=True):<br>    // Top 6 docs in each topic.</pre><p>The final stage of the pipeline is extractive text-summarization, via extracting the sentence in the corpus with the highest weight. Weight is calculated by frequency of weighted terms and sentence grammar score.</p><h3>Implementation —</h3><p>At the end of the pipeline we are able to classify topics into relevant/non-relevant in terms of “newsworthiness” buckets with a high degree of accuracy and cluster the classified tweets into modeled buckets with a reasonable degree of accuracy via a combination of unsupervised topic modeling and entity-extraction algorithms.</p><p>The cost of building a classifier with a high degree of accuracy is that it’s not very generalizable across categories since features which determine relevance often differ across categories. We’d ideally like to build a single classifier for classifying tweets across categories but such a classifier will sacrifice accuracy of predictions for generalizability. Instead we choose to have a few classifiers for category buckets which can classify tweets for topics within the category bucket with a high degree of accuracy.Further exploratory clustering can be done on the basis of sentiment and time-decay metrics to provide even more granular clusters. Also a shout-out to the maintainers of the following awesome packages which make text-based ML so much fun to work with — SKLearn, Spacy, Textacy, Gensim</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdcaee7542d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/experiences-building-a-newsfeed-out-of-twitter-streams-fdcaee7542d1">Experiences building a newsfeed out of twitter streams</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast-paced Authoritative MMO Data-Models]]></title>
            <link>https://medium.com/hackernoon/authoritative-mmo-data-models-5dc4c1aa30fa?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5dc4c1aa30fa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[virtual-reality]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 15:00:22 GMT</pubDate>
            <atom:updated>2019-04-23T09:44:18.221Z</atom:updated>
            <content:encoded><![CDATA[<h4>State synchronization across connected virtual-worlds</h4><p>Multiplayer immersive game development is one of the most interesting projects for indie creators and teams alike, presenting challenges covering a wide-spectrum from user experience to distributed computing.<br>From Minecraft to WoW open ended <a href="https://hackernoon.com/tagged/mmos">MMOs</a> have entertained and educated us and created communities for gamers and trolls alike and also pushed the boundaries of our <a href="https://imgur.com/a/XfCkQ">collective creativity</a> and <a href="https://www.gamespot.com/gallery/17-amazing-minecraft-creations-that-will-blow-your/2900-84/">imagination</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYWuY4Qgf-FBN1yrHIxHbw.jpeg" /><figcaption>King’s landing recreated in Minecraft [<a href="https://imgur.com/a/XfCkQ">Source</a>]</figcaption></figure><p>In recent years, MMO game-dev has seen a transition from intricate worlds created via hundreds of thousands of lines-of-code to player-defined worlds which provide building blocks for creating persistant artifacts and experiences. As the cutting edge in game economics, storage and UX technologies hit mainstream applications, it’s not overtly optimistic to assume that we’ll see some truly amazing MMO gameplay and immersive virtual worlds in the time to come..</p><p>For some perspective, WoW at its peak had <a href="https://us.battle.net/forums/en/wow/topic/20759278922">12 million</a> monthly active players. LoL which is the largest online Multiplayer game has over a <a href="https://www.riftherald.com/2016/9/13/12865314/monthly-lol-players-2016-active-worldwide">100 million</a> monthly active players (Although it is not really a MMO and maintains rooms of 10 players hosted on a single shard). By contrast, Youtube has <a href="https://techcrunch.com/2017/06/22/youtube-has-1-5-billion-logged-in-monthly-users-watching-a-ton-of-mobile-video/">1.5 Billion</a> monthly active users and Facebook has <a href="https://www.statista.com/statistics/264810/number-of-monthly-active-facebook-users-worldwide/">2.2 billion</a> monthly active users. Last year during Oculus conference, Mark Zuckerberg gave a <a href="https://www.facebook.com/zuck/videos/10103154531425531/">teaser</a> of things to come…</p><p><strong>Why you s̶h̶o̶u̶l̶d̶n̶’̶t̶ absolutely should be creating a MMO —</strong></p><p>Client SDKs, game-networking and cloud-native database stacks provide standardized solutions for most common access-patterns. It has historically never been a better time for creative professionals and programmers to come together and create MMO prototypes for emerging clients. Crowd-funds and ICOs have often removed the barriers the for indie game developers and small teams to go from prototype to production. Here are some major technological and social factors that will propel immersive world applications into the future.</p><h4>1. Liquidity for game tokens in the real world</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*yKv1aXW7ul1nLeS2rONccw.jpeg" /><figcaption>Liquid game tokens can be created on the blockchain</figcaption></figure><p>It’s far too long been the case that the only multiplayer games outside of big production studios making money were the ones which provide services with <a href="https://en.wikipedia.org/wiki/Fiat_money">Fiat</a> such as Poker or Betting games..Game currencies, such as <a href="https://en.wikipedia.org/wiki/Economy_of_Second_Life">Linden Dollars</a> (the currency of Second Life) while pioneering struggled to gain credibility and acceptance.. mostly because they were created out of thin air by game studios…many recently published white-papers and proof-of-concepts illustrate that game token and <a href="https://blog.enjincoin.io/12-ways-blockchain-will-disrupt-the-video-game-industry-5b9a4adb2f58">virtual world currencies</a> are one of the most natural use-cases of the blockchain. For instance, if the currency earned through industry in the virtual world can then be used in the real world and vice-versa and we’ll see many more interesting artifacts and development in immersive massively multiplayer landscapes. imagine you being able to hold an auction for the house or the bridge you built in Minecraft in game tokens and being able to convert the game tokens immediately to <a href="https://en.wikipedia.org/wiki/Fiat_money">Fiat</a>.</p><h4>2. Production ready VR SDKs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*aaafFmZ7WxOdoU3JCxdR-A.png" /><figcaption>Good news everyone ..and not just through <a href="https://theinfosphere.org/File:Netsuits.png">netsuits</a></figcaption></figure><p>Virtual Reality and Augmented reality have finally crossed the peak of inflated expectations and are almost past the trough of disillusionment of the the G<a href="http://phase of the gartner cycle and we are almost halfway through the disappointment phase">artner hype cycle</a> as real world usages are being tested and factories are creating production lines. From Unity and Unreal Engine major game engines are providing VR app client SDKs natively and vendors are already churning out VR devices for niche use-cases.</p><h4>3. Micro-services enabled seamless gameplay across clients</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqX9dW4xksliIBdrK9AD2Q.png" /><figcaption>The most played MMOs will provide cross-client experiences</figcaption></figure><p>When the app middleware is built as micro-services, it allows you-the game developer to support gameplay for multiple game clients and progressively enhance game play for more advanced clients. Imagine an MMO where players can do the full spectrum of actions such as participate in battles via the oculus rift client but are also able to chat with other players or water their garden via the android client.</p><h4>4. Cloud-native, auto-sharded distributed storage engines</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcpYj6seZxVbFjgQcaRmjg.png" /><figcaption>Cloud native databases provide consistent low latency reads and writes across regions and zones</figcaption></figure><p>Network latency has been the issue with playing online games even at moderately high FPS. This is because any network traffic over the public internet will incur latency resulting in considerable lag. Using dedicated networking provided by cloud service providers, we can limit the interaction with public internet to the last few hops, drastically improving P99 latencies over a large number of reads and writes. Advances in distributed database technology supporting multiple access patterns and providing fast reads and writes means that a lot of game networking and load-balancing logic can move from the middleware, down to the data layer.</p><h3>Game middleware architecture</h3><h4>1. Authoritative servers and dumb clients</h4><p>To the user the client is the game, clients will render all the graphics and allow user actions, the game client can be as rich as <a href="https://www.runescape.com/splash">Runescape</a> or <a href="https://worldofwarcraft.com/en-us/">WoW</a> or as simple as <a href="http://slither.io/">slitherio</a>. The client should not however authoritatively execute any logic based on user action and must act on values provided by the server. The reason for this is that we must always assume that the client is an attacker when developing a game in multiplayer contexts. For instance if the client were allowed to dictate it’s position and propagate it to other clients, it may become trivially easy for a malicious player to hack their coordinates and set it to be on the enemy flag and propagate it’s position to other very confused clients. It’s also easy to see how an authoritative server architecture scales better than authoritative client architectures.</p><p>Instead for every user action, the client must encode the state into a data structure and pass it down to the server which then interprets it against the rules of the game to see if the action makes sense, it then sends the position back to client which then regards it as it’s final position.<br>Additionally the server might take a batch of such inputs and run it against an analytics and inference engine to verify player actions. For instance did the player just hit 10 out his last 10 shots, are the mouse clicks on the screen differing from input coordinates?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DDWmWx6uIuukCzcLqFCQg.png" /></figure><h4>2. Network latency and state propagation</h4><p>Having authoritative server means that clients cannot cheat but it also means that the when you press the key W, the client sends the request and waits for the server response to tell it to move forward, when this happens over the internet it will visibly cause lag in the game experience. To get over this game clients use several smoothening techniques such as client side prediction, server reconciliation and interpolation. This article does not go into the details of client side compensation techniques, you can check out this <a href="http://www.gabrielgambetta.com/client-server-game-architecture.html">excellent explanation</a> here which also includes this <a href="http://www.gabrielgambetta.com/client-side-prediction-live-demo.html">demo</a>.</p><p>On the server side, we can reduce network latency by limiting the number of hops made over the public internet and by using high speed network peering provided by IaaS providers as much as possible. <a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> supports single click deployment and scale-up/down operations on primary nodes and read replicas in both AWS and GCP, while leveraging VPC peering to enable high speed networking and private traffic across regions and data centers.</p><h4>3. Server latency and linear scale-out models</h4><p><em>So how come we can have millions of people viewing the same webpage but only thousands on the same shard in an MMO?</em></p><p>In the article titled <a href="http://shamusyoung.com/twentysidedtale/?p=6185">MMO Population Problems</a>, the author explains how the network and server load multiplies exponentially on a MMO shard and the problems in handling state consensus in the application layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WjXNq9zPESst9kAJWr2Iag.png" /><figcaption>Scaling out from 25 to 50 nodes doubles read and write throughput <a href="https://blog.yugabyte.com/scaling-yugabyte-db-to-millions-of-reads-and-writes-fb86cea5ff15">Source</a></figcaption></figure><p><a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> DB solves the problem of scale by providing models that linearly scale-out instead of scaling up. For instance doubling the size of a 25 node cluster to 50 nodes causes the performance and throughput to double. You read the benchmark details <a href="https://blog.yugabyte.com/scaling-yugabyte-db-to-millions-of-reads-and-writes-fb86cea5ff15">here</a>.</p><h4>4. Automatic sharding and load balancing</h4><p>When creating game databases, teams are often faced with tough questions about the physical and logical partition of the data servers like — how many databases should I have per node? How should I decide which nodes I need to scale faster than others. This creates a chicken and egg problem in which you need to know access patterns of game interaction before you have actually built the game. <a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> simplifies this for game developers by providing auto-sharding data models from the outset that let’s you elastically scale out your cluster as your game grows.</p><p>The game servers could simply sit behind dumb load-balancers serving requests from nearest clients, which will in turn return the most recent consistent snapshot of the data maintained via <a href="https://docs.yugabyte.com/architecture/transactions/single-row-transactions/">MVCC</a>. Load balancing is handled on the data layer through <a href="https://docs.yugabyte.com/explore/auto-sharding/">auto-sharding</a> which automatically splits tables based on game models into multiple shards. This allows your team to not have to manage load-balancing in the application layer and your architecture would look more and more like if you were developing a single player game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEYcy95ha4WRyvS1_TYF0A.png" /><figcaption>Sharding of data into tablets. <a href="https://docs.yugabyte.com/architecture/concepts/sharding/">Source</a></figcaption></figure><h4>5. Read replicas for high-speed read access patterns</h4><p>MMOs access patterns usually follow frequent reads (for all the actors in the grid) and infrequent writes (for player actions)<br>In many access patterns where the actor is not writing but only reading, timeline consistent reads from async replicas may provide lower latencies. For instance if the player is not doing anything and only needs to read the data of all actors in their grid of reference, they can get timeline consistent copies from a Read-Replica. Read-Replicas may also be used to run cluster aware analytics jobs on live data to infer real time intelligence from player actions without straining the primary nodes.</p><h3>Efficiency of modeling APIs</h3><p>Games are computationally taxing applications and often test the limits of clients, networks and servers (on a scale), which is also the reason why efficiency matters most just just in the space it takes store the dirty state but also the code needed to serialize/deserialize it. Most MMO games follow access patterns dictating fast reads for the state of all objects in the player’s grid and fast write for the player’s information when the player does an action. Redis API provides simple constructs to store game state objects with minimal serialization/deserialization costs which can be used to build more complex structures. Often in browser games, the game state is passed down as a JSON document via HTTP.</p><h4>1. Redis Modeling</h4><p>Redis API provides developers with a set of very useful data structures such as sets, sorted sets, and hash maps that can be used to build more advanced structures that model most state transitions in MMO objects efficiently.</p><p>However traditional Redis implementations as a pure in-memory cache has its own limitations, the first is that the entire data-set needs to fit in-memory which might be a challenge for game servers with high user activity in a single shard. Another layer of complication is that implementing Redis + DB models requires further access pattern logic integrated into the application layer. <a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> solves this problem by providing a persistant Redis with Block-caches serving hot reads while providing sub-ms latency even for workloads that <a href="https://blog.yugabyte.com/achieving-sub-ms-latencies-on-large-data-sets-in-public-clouds-bf38d13ac42d">don’t fit the cache</a>. You can read more about <a href="https://docs.yugabyte.com/latest/api/redis/">YugaByte Redis</a> implementation <a href="https://blog.yugabyte.com/using-redis-as-a-true-distributed-fault-tolerant-database-8504a924a3f7">here</a>.</p><h4>2. CQL Modeling</h4><p>Fast access patterns for large datasets or those requiring strongly consistent distributed transactions such as marketplace transactions can be modeled over the CQL API. Moreover access patterns requiring range scans or queries that intuitively models the column family structure can be modeled via CQL API over the DocDB storage engine. YugaByte also supports Graph API access patterns via <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/janusgraph/">Janusgraph</a> and <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/kairosdb/">KairosDB</a> APIs for time series metrics.</p><h4>3. JSON Modeling</h4><p>MMO game states especially for web-based games are also often intuitively modeled as the JSON documents, Support for JSON type with Postgres API compatibility is in the works.You can find details about the PR <a href="https://github.com/YugaByte/yugabyte-db/issues/26">here</a>.</p><h3>Real-time Analytics over game state</h3><p>Any commercially viable virtual world will be running real-time analytics jobs on game data to gather intelligence on game play improvements, targeted advertising, cheating detection etc. Some examples of questions that you’ll likely be asking are —</p><ol><li>Is the matchmaker service matching players according to their skill levels?</li><li>Are some players cheating? If so how are they cheating?</li><li>What can I infer about player’s likes/dislikes etc. from gameplay patterns?</li><li>Are players clicking on in-game advertisements?</li></ol><p>Real time analytics using the <a href="https://www.yugabyte.com/solutions/use-cases/fast-data/">SKY stack</a> allows the services to be designed on top of the data layers which lets you infer meaningful knowledge from player actions.</p><h3>Simplifying the MMO data and operations stack</h3><p>Multiplayer game networking and state propagation is hard and definitely not something your team wants to focus on. While staying within the realm of what is feasible you want your models to be defined by providing the best user experience and not necessarily for minimizing data packets. <a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> DB can simplify a game engine server stack by combining the caching and persistance layer into one, pushing the load-balancing and sharding logic down from the application layer to the data layer and use the speed of Redis with persistance guarantees for in-game state and CQL APIs for Player data and web-service models.</p><h4>About me —</h4><p>I am a developer at <a href="https://www.yugabyte.com/">YugaByte</a> where we build data solutions for distributed, high-density applications and games. If you or your team are building immersive virtual-world experiences and exploring scale-out <a href="https://hackernoon.com/tagged/data-models">data-models</a>, you can check out the docs <a href="https://docs.yugabyte.com/">here</a>.</p><p><strong>Meanwhile you can head over to the </strong><a href="https://github.com/YugaByte/yugabyte-db"><strong>Github project</strong></a><strong> and take a deep dive into the code base.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5dc4c1aa30fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/authoritative-mmo-data-models-5dc4c1aa30fa">Fast-paced Authoritative MMO Data-Models</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On mental models of structure]]></title>
            <link>https://medium.com/@roypritam1234/on-mental-models-of-structure-and-order-5ed30a68d0ac?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed30a68d0ac</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[society]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[science]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Fri, 16 Mar 2018 09:28:50 GMT</pubDate>
            <atom:updated>2018-03-17T22:05:05.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Advanced alien races are probably using the same data-structures as us.</h4><p>The questions whether we are the only ones in the universe with sentience are perhaps as old as our civilization itself… Over the ages through progress of our own mental-models of Science, Math and Philosophy our models of the alien form has <a href="http://www.hawking.org.uk/life-in-the-universe.html">evolved</a> too… Starting in the late 19th century, with Nikola Tesla’s <a href="https://teslauniverse.com/nikola-tesla/articles/world-speaks-world-mysterious-signals-through-vast-space-tesla-electrician">attempt</a> to make contact with Martians via radio waves, we have continued to hopefully listen to the cosmos and broadcast our own messages via radio-telescopes through projects like the <a href="https://www.seti.org/seti-institute/project/details/project-phoenix">Project Phoenix</a> and the <a href="http://www.businessinsider.com/should-we-actively-try-to-contact-aliens-2015-3">SETI project</a>.</p><h3>A mental exercise in finding common ground</h3><p>If we ever encounter aliens, what commonalities can we expect to share with them? Will they be carbon based forms? Will they share out understanding of matter and the periodic-table? Will they comprehend our decimal number system?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTVt4BedNBpiRouDBOMuoA.png" /></figure><p>The alien models of linguistics will likely be <a href="http://astronomy.com/bonus/alien-contact">very different from ours</a> and so would their models of Biology, Physics and Chemistry. <a href="https://en.wikipedia.org/wiki/Alternative_periodic_tables">Alternative periodic tables</a> exist even here on Earth and it has been hypothesized that non-carbon based life-forms <a href="http://www.dailygalaxy.com/my_weblog/2011/05/stephen-hawking-on-non-carbon-based-alien-life.html">may exist</a> in the universe.</p><blockquote>What we normally think of as ‘life’ is based on chains of carbon atoms, with a few other atoms, such as nitrogen or phosphorous,We can imagine that one might have life with some other chemical basis, such as silicon. — Stephen Hawking, Life in the universe.</blockquote><p>For the aliens to be able to crack interstellar travel and visit us must mean that their models of Physics is at least a much more advanced form of ours ..for them to have figured out that <em>E = mc² </em>and then gone on decipher <a href="https://www.space.com/20881-wormholes.html">wormholes</a> instead of creating WMDs would be no small feat. This is also known as <a href="https://www.seti.org/seti-institute/project/details/fermi-paradox">Fermi’s paradox</a> which theorizes that the reason that intelligent life forms cannot find each other is that they destroy themselves before they can can figure out where they are in relation with the others..</p><p><em>If we were to rummage through an alien space-craft what artifact could we possibly find that we could immediately understand and appreciate?</em></p><p>Their tech would likely be more advanced to us than a smartphone to a neanderthal..their biology and language may be indecipherable too.. There is one thing however that we’ll likely find and be able to immediately understand and decipher.</p><p><strong><em>For them to have found us they must have had a map.. And the map would likely be a graph with places of interests marked as vertices.</em></strong></p><p>In the context of the cosmos finding Earth must be like finding <a href="https://phys.org/news/2016-07-earth-milky.html">a needle in a haystack</a>. In order to visit Earth, they must have had elaborate maps right up to the nearest wormhole in our Galaxy (assuming our models of space travel).</p><blockquote>If we ever meet intelligent life forms from another part of the universe, they’ll likely know, understand and recognize the same basic data structures we have in our computer science books. — Salvatore Sanfilippo, <a href="http://oldblog.antirez.com/post/redis-manifesto.html">The Redis Manifesto</a></blockquote><h4>But will the aliens be able to do Math?</h4><p>The idea of forming efficient structures for organization is intuitive to intelligent beings and do not necessarily need an understanding of Math.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*79lrdrTjf8WVMHtZQzN-yQ.jpeg" /><figcaption><strong>Can the ant do Math?</strong></figcaption></figure><p>The structures of information theory are however not bound by such considerations. The ant colony knows how to form efficient linked-list structures to get from one branch to another without having any understanding of Mathematics or formal reasoning.</p><h4><strong>Animals on Earth know how to organize into efficient structures.</strong></h4><p>Most life forms on Earth have an abstraction for society. The society that forms in groups and in doing so acquires a network intelligence. Through this network intelligence they stop being dumb animals and start forming optimal structures, the efficiency of which for a particular task can often often be proven mathematically even by our current <em>arguably limited</em> models of Mathematics. Let’s consider some basic structures of organization that are ubiquitous among animals on earth and we can expect the aliens to have the same understanding of mathematical structures as we do.</p><h4>The List abstraction</h4><p>The list is perhaps the most intuitive and most common transition from randomness to order found in nature. Often manifests in Information-theory as the array, the linked-list, the stack, the queue etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swZ5HUe6WkQsMj0svimIlA.jpeg" /><figcaption>The List is a commonly ococuring structure .[<a href="https://animals.howstuffworks.com/mammals/wildebeest-migration.htm">Credits</a>]</figcaption></figure><p>The list depending on how it’s modeled may allow for faster retrieval or insertions at the ends of an arbitrary positions. Animals will form a list structure when migrating, schools of fishes will form circular linked-lists in the oceans.</p><p>When we are standing in a supermarket checkout line we are forming a queue which allows for an <em>efficient</em> and <em>fair</em> system in which the person who enters first is served first. When we order our pillows on the bed we often form a tuple which is a form of list.</p><h4>The Row/Column abstraction</h4><p>The table structure is often seen in information theory as the two-dimensional array type. Several examples of structures can be found in nature too — the beehive can be modeled as tables where each which can be via a unique row-col index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2jDUqdThqJIdI5r-hDYuIA.jpeg" /><figcaption>The table structure allows for dense storage and indexing of artifacts [<a href="https://www.click.ro/utile/sanatate/un-miraculos-produs-al-stupului-capaceala">Credit</a>s]</figcaption></figure><p>Relational databases also expose the same row-column structure where every entity can be modeled as a set of properties in columns and values for the properties as rows. In a table each cell can be accessed via the row and column index which allows O(1) for easy retrieval but insertion at an arbitrary positions may be more expensive operations.</p><h4>The Graph abstraction</h4><p>A graphs is a set of vertices connected by edges. From the spider’s web to world maps we can find implementations of graphs everywhere in the real world as well as on our computer models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*m0EZAJSvVGzQLrFV7d7nVg.jpeg" /><figcaption>The graph (network of vertices connected via edges) is an intuitive way to model our universe.</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Graph_theory">Graph theory</a> itself is a vast topic with many many implications. On computer models as on paper graphs can be implemented in <a href="https://en.wikipedia.org/wiki/Graph_theory">multiple ways</a>, The spider models a graph as it’s home and for catching prey. Humans often use graphs to model relationships and places on maps and connected entities.</p><h4>Society as an abstraction for record-keeping and organization</h4><p>Record-keeping and organization forms the basis of civilization and society. Actions can have consequences only when there are records that can be referenced to the actions. Those records are stored on paper or in computers, indexed and organized in easily retrievable formats via data structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*EUbaSH1R9FOepIS2iGtNhQ.jpeg" /><figcaption>People self-organizing into efficient structures represent society</figcaption></figure><p>Every system that we see around us be it the judiciary or the city municipality can be abstracted as entities that are tasked with keeping records in their scope of jurisdiction. The progress of civilization can be seen as new and inventive ways of record-keeping. The computing revolution digitized our record keeping, now the blockchain revolution is decentralizing it. Those records which moved from notebooks to centralized servers are now moving into a public ledger nodes secured via cryptography as the authority figures transform from being sole guardians and proprietors of the data into mere overseers of it.</p><h4>Abstract structures for organization transcend time and evolution</h4><p>We have been using data structures for information storage and retrieval long before we formalized the structures with Information Theory. The scoreboards in gladiator matches in Ancient Rome were probably maintained in lists and tables similar to how League of Legends servers store match records albeit on a different storage medium. In a thousand years from now, when our computing has changed so much that it will be hard to trace it back to the humble beginnings of today, we’ll still continue to implement the same <a href="https://en.wikipedia.org/wiki/Abstract_data_type">abstract data types</a> that we do now, in more efficient ways using better underlying algorithms and on faster hardware. Perhaps abstract mathematics and information theory is after all the shared truth transcending time and life itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed30a68d0ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed transactions and why you should care]]></title>
            <link>https://medium.com/@roypritam1234/distributed-transactions-and-why-you-should-care-116b6da8d72?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/116b6da8d72</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Wed, 07 Mar 2018 18:28:02 GMT</pubDate>
            <atom:updated>2018-03-11T23:45:49.624Z</atom:updated>
            <content:encoded><![CDATA[<h4>If my product succeeds will this eventual-consistency thing come back to haunt me?</h4><p>Anyone who’s ever taken an information-theory class probably knows of <br><a href="https://stackoverflow.com/questions/3740280/acid-and-database-transactions">ACID properties</a> and the<a href="https://blog.yugabyte.com/a-for-apple-b-for-ball-c-for-cap-theorem-8e9b78600e6d"> CAP theorem</a>, but most people seem to think that this is a problem that only distributed system engineers need to be concerned about…<br><em>After all isn’t my database supposed to guarantee ACID properties for reads and writes across time and space?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DlLNPdqsA2fyxWARHmzMwA.jpeg" /><figcaption>Or you could just be that guy…</figcaption></figure><p>Why should I as an application developer concern myself with making sure that the transactions made by my application are propagated consistently and atomically across shards?</p><p>With changing data models however, the definition of what constitutes a “database” has shifted and the guarantees of ACID can no longer be taken for granted. Scale-out data models are faced with <a href="http://wiki.c2.com/?DistributedTransactionsAreEvil">unique challenges</a> with no perfect solutions and lots of trade-offs…and often the brunt of dealing with the consequences falls on the application programmer.</p><p>There are schools of thought on both sides of the equation, with eventual-consistency advocates arguing that <em>not all applications</em> need strong ACID guarantees across documents and the speed gains by giving up on ACID are worth it for a wide variety of use-cases. Other industry leaders and think-tanks advocate for strong-consistency in the data layer simply because it allows application developers to write scalable, bug free code without being distributed system experts themselves. In the <a href="http://static.googleusercontent.com/media/research.google.com/en/us/pubs/archive/41378.pdf">MillWheel paper</a>, Google advocates that the Data Layer must be strongly-consistent and be able to make distributed ACID transactions.</p><blockquote><em>By allowing users to focus solely on their application logic, this kind of programming model allows users to reason about the semantics of their system without being distributed systems experts. In particular, users are able to depend on framework-level correctness and fault-tolerance guarantees as axiomatic, vastly restricting the surface area over which bugs and errors can manifest.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*BMlveebSRAE7_wDvW9EO1w.jpeg" /><figcaption><strong>Drop all your assumptions about atomicity when developing on the cloud.</strong></figcaption></figure><p>But why is this such a hard problem? <br>Well, one of the problems is time itself.. it’s hard to get different systems to agree on a time, physical clocks hardly ever agree with each other.. and using networked time means that it takes time to send time. How do you maintain a sequential execution schedule when the nodes cannot reach a consensus regarding the order of operations? Logical clocks can be useful in globally sequencing events but often have no relation to physical time.</p><h3>The Distributed Data Model</h3><h4>When the database spans across the globe.</h4><p>Your start-up is now a unicorn and you start seeing orders coming in from all over the world. To cater to the growing customer-base, you scale out your cool NoSQL engine to additional regions and maybe even across public-clouds. Furthermore, to ensure faster reads across a single document, your database is now partitioned across clusters. How do you ensure that a transaction being committed on a node is propagated atomically to other nodes and no conflicting transactions are happening on the other node at the same time? How do you trade-off between availability and consistency in case of network-partition (node being down or heart-beat timeout)?</p><p>Multi-phase commit protocols and pessimistic read-write locking are solutions for ensuring atomicity in distributed transactions but they don’t help you much in case of network partitions. <br>Let us consider a sample application with both optimistic and pessimistic data models.</p><p><strong>Earth-to-Echo Travel Services — providing holiday packages to </strong><a href="https://newatlas.com/great-places-to-live-mars/45654/"><strong>premium Martian destinations</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*WFwF_-EAFBBNClgv4wNGGw.png" /><figcaption>Earth-To-Echo.. which consistency model do I choose?</figcaption></figure><p>Your micro-services based app allows honeymooners and business travelers alike to book shuttle tickets to Martian resorts. Obviously since Bitcoin is the currency that is acceptable in both Earth and Mars, you allow bookings to be made via Bitcoin.</p><h4>The optimist’s data model</h4><p>In the optimistic data model, the application asynchronously fires updates on the payments and tickets database and marks the transaction as success without waiting for any confirmations from the blockchain or the ticketing service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtKXvWq4D_FWR0HHiUaQ6w.jpeg" /><figcaption>The optimistic model is fast but doesn’t provide guarantees.</figcaption></figure><h4>The pessimist’s data model</h4><p>The pessimistic data model creates a blocking operation which holds the lock until the required number of confirmations have been received from the blockchain and then further holds it until ticketing confirmation has been received. If any one of the operation fails, It rolls-back the transaction and issues a refund if part 1 has already finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3nNsSXyKJg5ZICjGwAJ7A.png" /><figcaption>The pessimistic model provides guarantees but is slow</figcaption></figure><p>Practical models lie somewhere in between where provisional records created while transaction is still pending may allow nested transactions to continue while waiting for confirmation.</p><h3>Atomicity</h3><p><strong>All Or Nothing guarantees.<br></strong>Every business event must result in a single synchronous commit and the database must be the source of truth(Or as close to the truth as possible). In order for a Distributed Transaction to be atomic, it must be rolled-back if consensus cannot be achieved, so as to not leave the system in an inconsistent state.</p><h4>MVCC (Multi-Version Concurrency Control)</h4><p><strong>Or how to read a record without holding a lock on the artifact.<br></strong>MVCC is a protocol that allows <a href="https://docs.yugabyte.com/architecture/transactions/single-row-transactions/#hybrid-time-as-an-mvcc-timestamp">multiple timestamped versions</a> of the same artifact to be stored in the db. This in turn allows consistent reads from snapshots at the most recent timestamps to be made without holding locks on the writes. The most commonly used isolation model used with MVCC is the Snapshot Isolation Model.</p><h4>Clock-synchronization across the network</h4><p>By reconciling the time received between Atomic Clocks and GPS systems, the database can significantly reduce the bounded error on a global synchronized clock. A daemon in every node is checking in with masters trying to reach a consensus about the global time. A method known as <em>Commit-Wait</em>, then ensures that commits of related transactions are separated by at-least the bounded error. This method is known as <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/45855.pdf">TrueTime</a> — a flagship idea of Google.</p><p>Another common method of achieving globally-consistent timestamp consensus on distributed systems is by using <a href="http://users.ece.utexas.edu/~garg/pdslab/david/hybrid-time-tech-report-01.pdf">Hybrid Time</a> which <a href="https://docs.yugabyte.com/architecture/transactions/single-row-transactions/#hybrid-time-as-an-mvcc-timestamp">combines the advantages of physical and logical clocks</a>.</p><p>The Hybrid Time algorithm does not need to commit-wait for error bound in most cases and <a href="https://docs.yugabyte.com/architecture/transactions/single-row-transactions/#hybrid-time-as-an-mvcc-timestamp">ensures that </a>—</p><blockquote>Events connected by a causal chain of the form “A happens before B on the same server” or “A happens on one server, which then sends an RPC to another server, where B happens”, always get assigned hybrid timestamps in an increasing order.</blockquote><h3>Consistency</h3><p><strong>All nodes must see the same results of an operation at any given time.</strong></p><h4>Murphy’s Law (Or the pitfalls of an eventually-consistent model)</h4><p>Distributed Transactions on eventually-consistent models have rightly been called <a href="http://www.grahamlea.com/2016/08/distributed-transactions-microservices-icebergs/">the icebergs of micro-services</a>. As written by the author — <br><em>For those who think mostly about the happy paths in their system, distributed transactions will lie in wait, showing no harm day by day, until a little glitch happens in your network and suddenly all hell breaks loose.</em></p><p>In an <a href="https://blog.yugabyte.com/a-for-apple-b-for-ball-c-for-cap-theorem-8e9b78600e6d">excellent explanation</a> about the pitfalls of eventually-consistent and timeline-consistent models, Karthik, CTO of <a href="http://yugabyte.com/">YugaByte</a> and one of the <a href="https://books.google.com/books?id=A3CPDAAAQBAJ&amp;pg=PT56&amp;lpg=PT56&amp;dq=karthik+ranganathan+cassandra&amp;source=bl&amp;ots=vNwGo1Kz8n&amp;sig=afDUuY6CKH7onbgPO04YZGIvc9E&amp;hl=en&amp;sa=X&amp;ved=0ahUKEwi1ldDq4pTYAhVDzGMKHSTYAVoQ6AEIZzAN#v=onepage&amp;q=karthik%20ranganathan%20cassandra&amp;f=false">original authors of Cassandra</a> dispels myths about scalability of eventual-consistent models and an even bigger myth that strongly consistent (or CP systems) sacrifice performance.</p><p>Let’s consider an example from the banking domain. The <a href="http://gameofthrones.wikia.com/wiki/Iron_Bank_of_Braavos">Iron-Bank of Braavos</a> was known as the richest bank ever. We draw reference from the conversations between Cercei and <a href="http://gameofthrones.wikia.com/wiki/Tycho_Nestoris">Tycho</a>. The premise is that Iron Bank wanted confirmation that Jamie had arrived with the gold before increasing Cercei’s credit line and was simply not willing to take Cercei’s promise that the gold was on it’s way and will be repaid soon.</p><p>The fact that the banker was not willing to make a weakly-consistent transaction that could violate the ACID properties of the ledger prevented what could have possibly led to the downfall of the Lannisters and a swift ending to the war for the Iron-Throne :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LzG34T37JqOJwT4i8MxvOQ.jpeg" /></figure><p>Let us now consider what would have happened if the Iron Bank had an weak consistency model. Using Quorum Reads and Writes in an eventually consistent model will give inconsistent results in failure scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bme8zrn2ePiR3u16Zi-6ug.jpeg" /></figure><h3>Consensus Algorithms for Distributed Systems</h3><p>Consensus is the process by which multiple nodes agree on a single result to guarantee consistency among them. In the paper <a href="https://groups.csail.mit.edu/tds/papers/Lynch/jacm85.pdf">Impossibility of distributed consensus with one faulty process</a> the authors state that <em>no asynchronous protocol can always reach consensus in a bounded time, in the event of even a single node failure</em>.</p><h4>1. Two-Phase Commit Protocol</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*bKjTyUrMfEelAyK5OBHo-w.jpeg" /><figcaption>The manager collects the values in the voting phase and passes down a result in the commit phase which all participants must agree upon.</figcaption></figure><p>Perhaps one of the most widely used distributed consensus algorithms, this contains two phases — The Voting Phase and the Commit phase.<br>In the voting phase, the transaction manager asks every node for the result, then decides the correct value based on majority consensus and gives it back to the nodes. If everyone agrees, the transaction manager contacts every participants again to let them know about the final value. Otherwise, contact every participant to <em>abort</em> the consensus. The participants do not have to agree on a value but have to agree on whether or not to agree on the value provided by the Transaction manager.</p><h4>2. PAXOS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*oLYNA1A6DvlpVwW5JsETVQ.jpeg" /><figcaption>A fictional legislative council in the <a href="https://news.ycombinator.com/item?id=7108417">Paxos island of Greece</a>.</figcaption></figure><p><a href="https://lamport.azurewebsites.net/pubs/lamport-paxos.pdf">PAXOS</a> is a method of achieving consensus in a network with unreliable nodes. It contains the following roles — a Client which issues a request to the distributed system, Acceptors which form a quorum, a Proposer is an advocate for the client request trying to convince acceptors to accept it, a learner takes action once a request has been accepted, a leader is who is also a Distinguished Proposer and a Distinguished Learner. The leader then chooses the “valid result” and sends it to all the nodes, the nodes can reply with an accept or a reject. If a majority of nodes accept then the value is committed. <a href="https://github.com/apache/zookeeper">Apache Zookeeper</a> and <a href="https://cloud.google.com/spanner/docs/whitepapers/life-of-reads-and-writes">Google Spanner</a> use the PAXOS algorithm to achieve consensus.</p><h4>3. RAFT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*FKOzMp6LF9vVxEVe16A6Lg.png" /><figcaption>With strong leader election chosen through liveness and random-timeouts, RAFT has more practical implications than PAXOS.</figcaption></figure><p>The <a href="https://raft.github.io/">RAFT</a> consensus algorithm is similar to PAXOS in guarantees of performance and efficiency. It contains three actors — leader, followers and candidates. Leader election happens through heartbeats and random timeouts. The leader accepts log entries from clients and propagates them across clusters. <a href="https://github.com/YugaByte/yugabyte-db">YugaByte </a>uses RAFT to achieve consensus and arbitrarily add, remove or change nodes in the cluster in an online fashion. It can also tolerate the failure of a minority partition as long as enough nodes are online to hold a leader-election.</p><h4>4. PBFT (Practical Byzantine Fault Tolerance)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*rTyd4two9Wh6EhWAqj1TSQ.jpeg" /><figcaption>The byzantine-general trying to kill the consensus.</figcaption></figure><p><a href="http://pmg.csail.mit.edu/papers/osdi99.pdf">PBFT</a> is a consensus protocol that can tolerate Byzantine faults. Byzantine faults occur due to system failures or when all the actors are not behaving in altruistic ways. For eg. a byzantine fault may occur when an actor does not return any result, a deliberately misleading result or returns different results to different parts of the system.</p><h4>5. Proof Of Work</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RlE3UHB367ZaOjNtQezGeA.jpeg" /><figcaption>Random miner tries to mine the next block by solving a computationally challenging hash puzzle.</figcaption></figure><p>In a POW type algorithm, a random miner tries to mine the next block by spending huge computing resources. The block is then accepted and added to the chain. The majority is decided by the longest chain. The difficulty of mining is constantly changing to control block generation rate. Bitcoin, Ethereum and countless other digital currencies acquire consensus amongst nodes via POW. Since this a 1-CPU-1-Vote model, the attacker needs 51% of computing power to compromise the network.</p><h4>6. Proof Of Stake</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*0Kz8fArW4TasQfTyQ8m86Q.jpeg" /><figcaption>Everyone lays out their stake in the network and the greater the stake the greater the probability of mining the next block.</figcaption></figure><p>The more stake a candidate has the greater the chances of him/her mining the next block. POS implementations can be either Chain based on BFT based. <a href="https://www.reddit.com/r/NEO/comments/6usi4i/can_someone_explain_neos_pos_model/">Neo</a> and <a href="https://cardanodocs.com/cardano/proof-of-stake/">Cardano</a> are two currencies using POS to achieve consensus in the network. There are also proposals to move Ethereum to a POS consensus system in the Casper update.</p><h3>Isolation</h3><h4>Each Transaction must proceed as if it were the only one..</h4><ol><li><strong>Snapshot Isolation<br></strong>This isolation level guarantees that all the reads made on a particular timestamp are consistent across nodes and the transaction itself will successfully commit only if no conflicting updates are being made. MongoDB version 4.2 is <a href="https://www.mongodb.com/blog/post/multi-document-transactions-in-mongodb">likely to support</a> Snapshot Isolation for consistent reads across documents, culminating a multi-year engineering effort.</li><li><strong>Serializable Isolation<br></strong>This isolation level guarantees that all transactions would run in a linear(serializable) schedule.</li></ol><p><a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> supports snapshot-isolation with serializable isolation support being on the roadmap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVB0TPObpN2eaZTjAoSmDg.png" /><figcaption>Fine grained isolation locks for serializability (<a href="https://docs.yugabyte.com/architecture/transactions/isolation-levels/">Source</a>)</figcaption></figure><h3>Durability</h3><h4>All state changes must be persistant upon commit.</h4><p>For durability in distributed systems, the TimeStamps (Hybrid or Atomic) of each update need to be recorded, so that it is possible to recover the state of the document from any point in the past. These versioned updates need to subsequently be garbage collected when there are no transactions reading a snapshot at which the old value would be visible.</p><p><a href="https://github.com/YugaByte/yugabyte-db">YugaByte</a> uses a Log Structure Merge Tree based key-value store with updates being replicated via the RAFT protocol. The mutation of records are <a href="https://docs.yugabyte.com/architecture/concepts/persistence/">versioned using timestamps</a> and uses bloom-filters and range-query optimization for faster reads.</p><h3>Distributed Transactions in modern scale-out databases</h3><p>In the article <a href="https://blog.yugabyte.com/practical-tradeoffs-in-google-cloud-spanner-azure-cosmos-db-and-yugabyte-db-ce720e07c0fd">Practical Tradeoffs in Google Cloud Spanner, Azure Cosmos DB and YugaByte DB</a>, the author does quite well in explaining the trade-offs that need to be considered when choosing between the three scale-out databases. Here I will summarize some highlights from the text briefly —</p><h4><a href="https://cloud.google.com/spanner/">Google Spanner</a></h4><p>Google Spanner internally divides the data into chunks called <a href="https://cloud.google.com/spanner/docs/schema-and-data-model#database-splits">splits</a> and assigns each split to a different node. It then replicates each split and distributes them amongst the nodes using the PAXOS consensus algorithm. <br>Global clock synchronization is done via TrueTime which provides minimum bounds of timestamp error. Using commit-wait for error bounds, it is able to achieve External-Consistency meaning all transactions will follow a global serializable schedule even on nodes in different regions. Google Spanner however, is proprietary, works on specialized GCP hardware (cloud lock-in) and only supports a single API (SQL).</p><h4><a href="https://azure.microsoft.com/en-us/services/cosmos-db/">Azure Cosmos DB</a></h4><p>Azure Cosmos DB is a multi-model, polyglot distributed data solution with <a href="https://docs.microsoft.com/en-us/azure/cosmos-db/consistency-levels">5 different consistency levels</a> to choose from. It supports the Cassandra, Mongo and Graph APIs amongst others and uses proprietary replication and consensus algorithms. To prevent write unavailability in the case of partitions for the Strong-consistency mode of operations, it limits accounts with strong consistency guarantees to a single Azure region. It is not open-source and works only on Azure hardware (Cloud lock-in).</p><h4><a href="https://www.yugabyte.com/">YugaByte DB</a></h4><p>YugaByte is an infrastructure-agnostic, distributed data-store which can be deployed across <a href="https://docs.yugabyte.com/deploy/public-clouds/">Public Cloud</a> and OnPrem datacenters. YugaByte DB <a href="https://docs.yugabyte.com/explore/auto-sharding/">shards</a> the data into a configurable number of tablets, which are then distributed evenly amongst the nodes in the cluster. Each tablet is further <a href="https://docs.yugabyte.com/architecture/concepts/replication/">replicated</a> in the other nodes via the RAFT consensus algorithm.<br>It provides Strong Consistency guarantees across regions and zones, uses hybrid timestamps for global timekeeping and provides <a href="https://docs.yugabyte.com/architecture/transactions/isolation-levels/">snapshot isolation</a> via MVCC with serializable isolation being in the works. The codebase is <a href="https://github.com/YugaByte/yugabyte-db">open-source</a> and compatible with <a href="https://docs.yugabyte.com/api/redis/">Redis</a>, <a href="https://docs.yugabyte.com/api/cassandra/">Cassandra</a> and <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/janusgraph/">Gremlin</a> APIs and SQL support being in the works.</p><h3>Because what matters is the system behaving in consistent, predictable ways..</h3><p>Any distributed data-store — be it a database, a messaging queue or a blockchain must behave in consistent and predictable ways even in cases of network failures and as application developers, we must be mindful of the choices that we make when choosing a data model because it will come to define the life of the product you are building and everything surrounding it.</p><p>If you liked this article there’s 50 ways(claps) to show you appreciation :)</p><h3>Further Reading -</h3><ol><li><a href="http://nighthacks.com/jag/res/Fallacies.html">Fallacies of Distributed Computing.</a></li></ol><p>2. <a href="https://www.cs.rutgers.edu/~pxk/417/notes/content/transactions.html">Distributed Transactions- ACID and BASE.</a></p><p>3. <a href="https://docs.yugabyte.com/architecture/transactions/isolation-levels/">Isolations levels in Distributed databases.</a></p><p>4. <a href="https://docs.yugabyte.com/architecture/transactions/transactional-io-path/">Transactional IO using provisional records.</a></p><p>5. <a href="http://the-paper-trail.org/blog/a-brief-tour-of-flp-impossibility/">A brief tour of FLP impossibility</a></p><p>6. <a href="https://lamport.azurewebsites.net/pubs/time-clocks.pdf">Time, Clock and order of execution of events in a distributed system.</a></p><p>7. <a href="https://www.worldcat.org/title/honeybee-democracy/oclc/587249075">Honeybee democracy — actor behaviour when given equally lucrative choices</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=116b6da8d72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending the Tangle network to a distributed cloud]]></title>
            <link>https://medium.com/swlh/extending-the-tangle-network-to-a-distributed-cloud-2f5857db02f5?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5857db02f5</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Sat, 17 Feb 2018 17:30:02 GMT</pubDate>
            <atom:updated>2018-02-21T05:41:25.559Z</atom:updated>
            <content:encoded><![CDATA[<h4>Some thoughts on the technical and social architecture of a machine-economy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFtWCQpFN2fHWIsYdAgDow.jpeg" /><figcaption>What is needed for the future to happen? [<a href="https://www.linkedin.com/pulse/more-connected-future-meg-whitman/">ImgSource</a>]</figcaption></figure><p>The idea of <a href="https://data.iota.org/">data-markets</a> backed by digital currencies has been floating around for some time now. This article talks about the software infrastructure needed to build such data-markets and what such markets might look like using the IOTA protocol as the hypothetical “currency” for data-exchange.</p><p><em>Throughout this article we can theorize IOTA as a handshake-protocol and as an immutable ledger of machine-to-machine transactions rather than as a platform to run smart-contracts on or as a speculative currency.</em></p><p>The currency to run a machine-economy should have the following features — <em><br></em><strong>Support micro-transactions.</strong><br>Single machine transactions may be orders of magnitude lower than typical human transactions and much higher in volume, ideally the network fees should be very close to zero to realize micro-transactions at any scale.<br><strong>Support transactions-at-scale</strong>.<br>Machine transactions will be much more frequent and will quickly out-number human transactions when introduced into any market, for an example check the order book at any trading index with a public API.<br><strong>Provide Security to the network.<br></strong>The cryptographic hash generated through an IOTA handshake can then be used to secure the data.<em> </em>The transaction protocol will be in some sense the backbone of such a network and also be the security blanket.</p><p>When such a network is extended to include high-powered cloud based nodes running specialized storage/processing software, we can enable a new ecosystem of real time decision-making through machine intelligence, leveraging the localized decision making of the network combined with the collective wisdom of the cloud.</p><h4>An incentives based society rewarding good actors in real-time.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcJijib0RuPKE01x-NQ5CA.png" /><figcaption><strong>The future of governance will likely be incentive based..</strong></figcaption></figure><p>The future of governance will perhaps be about creating economic incentives for actors to behave responsibly. If you drive within the limits, you’ll be rewarded by the system in micro-payments, your insurance rates will go down in real-time ..eventually the only actors who oppose the system and refuse to share their data will be the bad actors, game theory and market equilibrium will propel society into this machine economy.</p><h3>But wait.. what do we need the cloud for?</h3><h4>Or isn’t IOTA supposed to drive perfect networked systems?</h4><p>Ok, Let’s imagine a perfect <a href="https://www.cisco.com/c/dam/en_us/solutions/trends/iot/docs/computing-overview.pdf">Fog network</a> where every machine is given equal weight(computing power) and workloads are evenly distributed amongst all nodes. <br><strong>But.. that’s not how it works in the real world !!<br></strong>Exactly.. your Mac has more computing power that your fridge and your Mac has less computing power than a c3.4xlarge machine sitting in an AWS data-center.</p><p>Phones usually don’t want to run computation heavy workloads nor do you want to download the software on them to do so.</p><p><strong><em>Even in a Fog scenario, certain kinds of computations will be more suited to a certain class of machines than others and hence even in the perfect fog clouds will emerge..</em></strong></p><p>The Cloud in this context is a node in the network with a reasonable amount of storage to run a data-storage process and processing power to run a compute cluster process and is assumed to be sitting in a given “Infrastructure as a service”. The Cloud machine also has it’s own wallet and is usually running a full node and performing micro-transactions at scale while performing distributed storage and analytics processes on the data.</p><p>In this future, where the concept of ownership is made obsolete, the devices we use and sensors in the public domain will essentially become fleets run by corporations and corporations need to converge data from various sources. Which is why the swarm must interact with a a <a href="https://raft.github.io/">trustless</a> cloud to run broader business decisions. Each node has it’s own view of the world and provides a unique insight which could also form the basis of deeper learning models.</p><p>This discussion attempts to delve a bit deeper than mere nomenclature and explore the possibilities that such data driven economies would create and the <a href="https://blog.yugabyte.com/yugabyte-db-architecture-diverse-workloads-with-operational-simplicity-cdf82483a1fb">infrastructure</a> suited to doing so, in discuss the possibility of building such an infrastructure using the <a href="https://www.yugabyte.com/solutions/use-cases/fast-data/">SKY Stack</a>, a distributed streaming-data software-only stack.</p><h3>So what use-cases will this “machine-economy” enable?</h3><p>IOTA as it stands today is a <a href="https://coinmarketcap.com/currencies/iota/">quaint</a> cryptocurrency with not too many use-cases extending beyond Binance and Bitfinex, However in a future, combined usages by machines at scale can create networked intelligence which combined with <a href="https://medium.com/swlh/why-fast-data-is-suddenly-everywhere-3bb25bfff3b9">fast-data technology</a>, can enable massive data-markets which will dwarf the databases of today. The fact that your machines(you) will sell associated device data in real time can(will) enable cool(or creepy) use-cases like data-markets where your personal (device) data is being brought and sold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4Lj4ZH6Hn9fdoVSR7K6UQ.jpeg" /><figcaption>In this universe people sell their data for a living</figcaption></figure><p>But why would anybody be interested in the pings from my apple-watch you ask..well it’s not just you but who you are at a given point.. your smart-building may want to know when you are around so that it can get a headcount and adjust building temperature, this will help it cut costs and it’ll pay your device for streaming pings.</p><p>The restaurant you visit may want to know if they have seen you before so that can provide recommendations, order supplies in real-time etc.. It is your situational data, combined will that of others in the network which form complex relationships at a given time that can help a business make a decision or reach a goal and they’ll pay your device for it.. in a constant stream of usage based micro-payments where nothing is lost to transaction fees.</p><h3>And what about the software stack?</h3><p>The requirements for a software stack to handle the scale of connected cities will be massively parallelized, distributed real-time computing and storage.</p><ol><li>Data streams must be cryptographically secure. This is achieved through a proof of work type system where both the source and sink must perform some work (in this case approve two other transactions) to secure the network.</li><li>The computation layer must be distributed and support acyclic data flow.To enable fast-analytics on a massive scale of public IOTA networks the computation layer should be <a href="https://www.infoworld.com/article/3014440/big-data/five-things-you-need-to-know-about-hadoop-v-apache-spark.html">memory-based</a> and run optimized storage DAG based queries.</li><li>The IOTA network propagates data through an implementation of the Gossip Protocol and is as such <a href="https://www.tangleblog.com/2017/01/25/the-tech-behind-iota-explained/">eventually-consistent</a>. The data model needs to be strongly-consistent in order to be the source of truth for transactional use-cases, support <a href="https://docs.yugabyte.com/explore/transactions/#nav_bar">Distributed ACID transactions</a> and be able to handle <a href="https://blog.yugabyte.com/yugabyte-db-architecture-diverse-workloads-with-operational-simplicity-cdf82483a1fb">a variety of workloads</a>. You can read an excellent description of the<strong> </strong>CAP theorem <a href="https://blog.yugabyte.com/a-for-apple-b-for-ball-c-for-cap-theorem-8e9b78600e6d">here</a>. There is also an interesting paper of learning <a href="https://www.microsoft.com/en-us/research/publication/replicated-data-consistency-explained-through-baseball/?from=http%3A%2F%2Fresearch.microsoft.com%2Fpubs%2F157411%2Fconsistencyandbaseballreport.pdf">eventual consistency through baseball</a>. You can read an introduction to <a href="https://web.stanford.edu/~ouster/cgi-bin/papers/raft-atc14">RAFT protocol</a> here. You can also read, YugaByte specific implementation details <a href="https://docs.yugabyte.com/architecture/concepts/replication/">here</a>.</li><li>The data and compute model needs to be trustless, massively distributed and scalable to hundreds of nodes and be able to support high-volume <a href="https://blog.yugabyte.com/scaling-yugabyte-db-to-millions-of-reads-and-writes-fb86cea5ff15">concurrent reads and writes</a>.</li><li>The data layer must support multiple APIs to enable different kinds of models most intuitive to the given machine-economy use-case. Business requirements based on the Tangle network may be most intuitively modeled through a Graph API. Requirements for massive parallel computing and real-time streaming analytics are more easily modeled in a denormalized SQL or CQL models when we don’t want to do expensive JOINS in real-time and duplication is acceptable. Requirements for extremely fast cache reads may be best modeled in a Redis like API.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*REwzSRGEmhZLm95cjeaLSQ.png" /><figcaption>Architecture of a machine-economy</figcaption></figure><h4><strong>How do we model the connected machines?</strong></h4><p>How do you model a public IOT fleet with hundreds of thousands of nodes each performing thousands of micro-transactions.. Is this a graph problem or a time-series problem? Use-cases modeling on the tangle graph can be most intuitively modeled over a <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/janusgraph/">graph API</a>, other more data query centric views or time-series oriented views may require modeling over the <a href="https://docs.yugabyte.com/api/cassandra/">CQL API</a>. The sensor data emissions can also be modeled as a time-series problem as well. While some models are represented better in SQL others such as those doing fast-analytics on streaming data are better represented in columnar CQL models.</p><p><strong>Data cannot exist in Silos<br></strong>The IOTA chain is Partition tolerant and thus allows for offline transactions, In a massive public network, nodes could span over major public-clouds or on-prem datacenters. The data layer connecting IOTA nodes must be infrastructure agnostic. The network as a whole must be able to update it’s state of the world.</p><h3>A bottom-up view of the architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3MBwweZZRx8Jzfugnis4g.png" /><figcaption>The view from the Cloud</figcaption></figure><h4>Apache Spark</h4><p>What do Apache Spark and Tangle have in common? They both use <a href="https://stackoverflow.com/questions/25836316/how-dag-works-under-the-covers-in-rdd">Directed Acyclic graphs</a> to perform their computations. A Spark network can perform analytic queries on the edge and stream the data to sinks or write back to the storage. This cleaned real-time analytics data can then be further streamed to clients via 3rd party data- markets which may perform a similar handshake on their side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hzzif05ML1H4hyB6Win9Fw.png" /><figcaption>Spark Streaming models with the SKY stack.[<a href="https://www.yugabyte.com/solutions/use-cases/fast-data/">Source</a>]</figcaption></figure><p>Here’s what a typical <a href="https://www.yugabyte.com/solutions/use-cases/fast-data/">SKY stack</a> architecture looks like. A “network aware” Spark architecture can interface seamlessly with YugaByte storage engine via the Cassandra API.</p><h4><a href="https://github.com/yugabyte/yugabyte-db">YugaByte DB</a></h4><p><a href="https://www.yugabyte.com/">YugaByte</a> is a <a href="https://blog.yugabyte.com/achieving-sub-ms-latencies-on-large-data-sets-in-public-clouds-bf38d13ac42d">fast</a>, strongly-consistent, distributed, scale-out database designed to handle ever growing data networks like that of the tangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNC1sQV3Uu2LbzD1qNbKnA.png" /><figcaption>Elastic data cluster with support for Redis and CQL APIs</figcaption></figure><p>It achieves consensus amongst nodes using a modified version of the <a href="https://raft.github.io/">RAFT protocol</a>.</p><p>The <a href="https://blog.yugabyte.com/practical-tradeoffs-in-google-cloud-spanner-azure-cosmos-db-and-yugabyte-db-ce720e07c0fd">design choice</a> made is to give away availability in favor of consistency on failure occurrence while also limiting the loss of availability to only a few seconds till the new tablet leaders get elected. It supports <a href="https://docs.yugabyte.com/api/cassandra/">Cassandra</a> and <a href="https://docs.yugabyte.com/api/redis/">Redis</a> APIs out of the box and can be plugged into <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/janusgraph/">Graph APIs</a> which allow for models that fit various streaming transactional-data use-cases with strong consistency guarantees. The storage engine <a href="https://blog.yugabyte.com/building-a-strongly-consistent-cassandra-with-better-performance-aa96b1ab51d6">beats open-source Cassandra</a> in YCSB benchmarks and provides sub-ms latency in networked environments and works out of the box on AWS, GCP or OnPrem. You can see comparisons with other distributed SQL and NoSQL databases <a href="https://docs.yugabyte.com/comparisons/">here</a>.</p><h4>JanusGraph</h4><p><a href="https://github.com/JanusGraph/janusgraph">JanusGraph</a> is a graph query layer for both OLTP and OLAP systems and works quite well with distributed scale out databases. It is an implementation of the Gremlin protocol, optimized for storing a large number of vertices. Graphs can provide powerful intuitive query models for relationships that naturally represent networks. You can read more about ecosystem integration with the storage layer <a href="https://docs.yugabyte.com/develop/ecosystem-integrations/janusgraph/">here</a>.</p><h4><strong>Apache Kafka</strong></h4><p><a href="https://github.com/apache/kafka">Apache Kafka</a> is a distributed streaming platform and used as a data collector for the streaming devices. It is in this layer that the decryption of the data will be performed and the IOTA transactions will be made.</p><h4>IOTA API</h4><p>IOTA transactions can be used to cryptographically sign and verify the correctness of streaming data.<br>You can also read more about Masked Authentication Messaging protocol <a href="https://blog.iota.org/introducing-masked-authenticated-messaging-e55c1822d50e">here</a>. IOTA fits in the eco-system as it’s da-facto currency. The transaction will also generate an access key which will be used to cryptographically secure the streams.</p><h3>Simulating a Machine Economy</h3><h4><strong>Traffic Management in the cities of the future</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*SjnLeU0BJAm1L-6LathbIQ.jpeg" /><figcaption><strong>Your Mustang’s wallet was just charged 1k MIOTA and here’s your ticket..</strong></figcaption></figure><p>In a world-view where compliant vehicles have a GPS emitter and a multi-sig wallet. The city traffic system is monitoring all running vehicles in real-time. The system is sending IOTA to vehicle wallets in return for for heart-beats with a json payload over a fixed-period of time. This data can be used to form complex models in real-time and answer many analytical as well as general queries about the state of the world at any given point.</p><h4>Premise</h4><p>Each vehicle emission contains the co-ordinates of the vehicle and the time-stamp at which is was sent. It is collected into the Akka sink and is fed a YugaByte node. YugaByte can run Spark on the same nodes as the database.</p><h4>Handshake</h4><p>The handshake can be done via a protocol similar to Open Authentication protocols that we have today. Each transfer will create an access token and a refresh token, every <em>X</em> seconds the access token will expire and a new one will be generated with a micro-payment of <em>n</em> IOTA.</p><h4>Data Models</h4><p>Let’s create two simple CQL Data Models and show some powerful queries we can run. (Production time-series models may need to be partition and cluster aware, check out this <a href="https://www.datastax.com/dev/blog/advanced-time-series-data-modelling">tutorial</a> to learn more)</p><pre>// CQL can be used for transaction hash models and business models // based on device metadata use-cases.</pre><pre>// A simple model of vehicle emissions by time-stamp<br>CREATE TABLE vehicle_emissions<br> (vehicle_id varchar,<br> event_ts timestamp,<br> vehicle_lat float,<br> vehicle_long float,<br> location text PRIMARY_KEY (vehicle_id, event_ts));</pre><pre>// Another model of vehicle emissions by street<br>CREATE TABLE vehicle_on_street_events<br> (vehicle_id varchar,<br> event_ts timestamp,<br> street_id varchar PRIMARY_KEY(event_ts, street_id));</pre><h4>Real-Time Intelligence</h4><p>Once we have a stream of lat-longs emitted by a vehicle we can use it to approximate the Speed(velocity) in near real-time. We can do feed it to Spark Streaming combined with historical data reads .</p><p>The<a href="https://www.yugabyte.com/solutions/use-cases/fast-data/"> SKY stack</a> which consists of Spark, Kafka and YugaByte can be used to model such use-cases.</p><p>Get me the speed of the car with uuid CA1234 over last 20 mins.</p><pre>SELECT lat, long, location<br>FROM vehicle_emissions<br>WHERE vehicle_id=&#39;CA1234&#39;<br>  AND event_time &gt; ’2026-06-03 07:01:00′<br>  AND event_time &lt; ’2026-06-03 07:21:00′;</pre><pre>// Between any two pings<br>// distance = √((<em>x2</em>-<em>x1</em>)^2 + (<em>y2</em>-<em>y1</em>)^2)<br>// velocity = distance / interval_between_pings</pre><p>If your access patterns dictate that after this you do an operation like-</p><p>Get me the details of the vehicle with vehicle_id CA1234 then rather than doing an join on the application layer you update your CQL model to include the new data (Based on the premise that storage is cheap and it is ok to duplicate data as long as we can reduce seeks).</p><h4>Alerting</h4><p>Aggregated streaming location data can lead to powerful inferences.</p><pre>SELECT lat, long, location<br>FROM vehicle_emissions<br>WHERE vehicle_id=&#39;CA1234&#39;<br>  AND event_time &gt; ’2026-06-03 07:01:00′<br>  AND event_time &lt; now();</pre><pre>&gt; Pipe result-set to inference-engine to compare vehicle movement patterns against normal vehicle movement patterns on the road.</pre><pre><em>ALERT: Erratic Driving patterns observed on Highway 280. Possible DUI.</em></pre><h4>3rd party Data-Markets</h4><ol><li><strong>Insurance</strong> <br>The system can pipe data to insurance providers who can make inferences in insurance claims such as car collision with speeds in time frames.</li></ol><pre>SELECT lat, long, location<br>FROM vehicle_emissions<br>WHERE vehicle_id=&#39;CA1234&#39;<br>  AND event_time &gt; ’2026-06-07 09:01:00′<br>  AND event_time &lt; ’2026-06-07 09:04:00′;</pre><pre>// Calculate second-order derivative of rate of change(Deceleration) of vehicles between continuous heartbeats.<br>// Infer whether the car in-front suddenly braked to cause the car behind to bump into it.</pre><p>2<strong>. Forensics<br></strong>The system can pipe data to forensics and detectives who can then use it to investigate cases.</p><p><em>Give me the UUID of all cars which turned left from Dolores on Saturday 12th Nov between 1AM and 2 AM.</em></p><pre>SELECT vehicle_uuid<br>FROM vehicle_on_street_events<br>WHERE street_id=&#39;CA4433&#39;<br>  AND event_time &gt; ’2026-06-07 09:01:00′<br>  AND event_time &lt; ’2026-06-07 09:04:00′;</pre><h4><strong>Also more “ETL Like” Queries</strong></h4><p><em>Give me the transactions made by all vehicles that went over 60 mph over the last 1 month.</em></p><p><em>Get me all the places that vehicle with uuid CA1234 has gone over the past one-month.</em></p><h4>So where do we go from here?</h4><p>Finally these musings are made possible through open-source projects that stroke our imagination and the devs working to make make them possible.<br>Check out these cool software integrations and see if you can come up with some interesting, futuristic, use-cases of your own. :)</p><p><a href="https://github.com/YugaByte/yugabyte-db"><strong>YugaByte DB</strong></a> — Distributed source-of-truth database[CP Database with High Availability]. (<a href="https://docs.yugabyte.com/">Docs</a>)</p><p><a href="https://github.com/apache/spark"><strong>Apache Spark</strong></a> — Distributed compute cluster using DAGs to perform acyclic order computations.(<a href="https://spark.apache.org/docs/2.2.0/">Docs</a>)</p><p><a href="https://github.com/iotaledger/iota.lib.js"><strong>IOTA JS </strong></a>— JS implementation of the IOTA library.</p><p><a href="https://github.com/apache/kafka"><strong>Apache Kafka</strong></a> — Process, Store, Publish and Subscribe events in Real-Time.(<a href="https://kafka.apache.org/documentation/">Docs</a>)</p><p>Interesting related reads —</p><p><a href="https://docs.yugabyte.com/architecture/transactions/distributed-txns/">Distributed ACID Transactions</a></p><p><a href="https://docs.yugabyte.com/develop/realworld-apps/iot-spark-kafka/">Sample SKY stack integration</a></p><p><a href="https://blog.iota.org/introducing-masked-authenticated-messaging-e55c1822d50e">Masked Authentication Messaging</a></p><p><a href="https://blog.yugabyte.com/a-for-apple-b-for-ball-c-for-cap-theorem-8e9b78600e6d">CAP Theorem</a> explained by an original author of Cassandra.</p><p>I have also begun somewhat of an effort to actually model some simulations. The github can be found <a href="https://github.com/pRoy24/tangled-economy">here</a>. <br>Remember If you liked the story there’s 50 ways(claps) to show your appreciation . ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by 297,332+ people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5857db02f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/extending-the-tangle-network-to-a-distributed-cloud-2f5857db02f5">Extending the Tangle network to a distributed cloud</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All the data we lost to incompatible APIs.]]></title>
            <link>https://medium.com/swlh/a-moment-for-all-of-our-data-lost-in-time-260a54fef86?source=rss-7a6b426a25b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/260a54fef86</guid>
            <category><![CDATA[yugabyte]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Pritam Roy]]></dc:creator>
            <pubDate>Sun, 04 Feb 2018 22:48:33 GMT</pubDate>
            <atom:updated>2018-02-18T02:50:51.738Z</atom:updated>
            <content:encoded><![CDATA[<h4>Chronicles of our data through time.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*WFx8Z7vxXXdFj9BsXDtTjQ.jpeg" /><figcaption><strong>Are we heading towards the dark ages of data?</strong></figcaption></figure><p>On February 2015, Vint Cerf, also known as the father of the internet, issued a <a href="https://www.theguardian.com/technology/2015/feb/13/google-boss-warns-forgotten-century-email-photos-vint-cerf">warning to humanity</a> - that of a possible dark age and a lost generation simply because the systems of the future will not be able to render the files of the present.</p><blockquote>“We are nonchalantly throwing all of our data into what could become an information black hole without realizing it. We digitise things because we think we will preserve them, but what we don’t understand is that unless we take other steps, those digital versions may not be any better, and may even be worse, than the artifacts that we digitised,”</blockquote><p>The decay of files simply because newer software/hardware doesn’t understand the format it was written in is called <a href="http://www.economist.com/node/21553445">Bit Rot</a> and happens with every new generation of storage, processors or software that comes along and renders the previous one incompatible and obsolete.</p><p><a href="http://www.economist.com/node/21553445">NASA recently stated</a> that they have lost access to tons of data from the early moon landings, because the machines used to read the tapes were scrapped and cannot be rebuilt.</p><p>We are losing, in some cases access to a over <a href="https://www.theatlantic.com/national/archive/2013/12/scientific-data-lost-forever/356422/">80% of scientific data</a> from the early days of computing and often not even realizing it and this is not a problem for some distant future.. we can no longer play many video-games from the 90’s because the consoles are incompatible or the distributors are no longer around. Rapidly changing standards coupled with the fact that we are destroying physical copies of old text while preserving “digital copies” means that we risk erasing not only the chronicles of our time but that of history itself.</p><h3>Are we falling backwards in time?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tdq9B6DzAWCpoXcaYq_0aw.png" /><figcaption><strong>The stories of the earliest human-beings etched in stones on the inside of caves have survived over thousands of decades.</strong></figcaption></figure><p>When we first started writing, we used clay tablets which survived in some cases for thousands of years, then we switched to a paper medium, it is more convenient to store information on paper but it also decays faster and the only paper writings we find today are the ones which had been carefully preserved through time and in some sense “deemed important”.</p><p>Paper writings and clay tablets however did not have a large cost to retrieve data as any one who could read and understand the language could read from the paper material.</p><p>In the information age however, there is a cost to storing data at scale - it involves the cost to run servers, pay for electricity and pay for people managing those servers, pay for upgrades when technology advances. There is a cost to retrieve it too, the users need to have hardware and software that can understand and render the format the file was written in.</p><p>Formats change, sometime due to technical reasons and other times due to purely political reasons. If Microsoft Word decides to stop supporting the docs format or if the PDF format is no longer accepted as better ones come along and over time hardware and software design takes a different direction.. in that future all of the research papers, financial reports, birth certificates and death records stored in pdf will be lost forever.</p><p><strong>As we are creating more data, we are also erasing our past often permanently. </strong>If a consumer web company gets acquired or liquidates, it has no incentive to keep it’s data centers running as what happened when Home automation company Revolv got <a href="https://gizmodo.com/nest-owned-smart-hub-gets-permanently-killed-1768977505">acquired by Google Nest</a> and its automation hub was shut down leaving owners of the smart home product feeling pretty dumb about their decision. Similarly a bank or a financial institution may have no incentive to keep transaction records beyond what is needed by business and regulatory requirements.<br>Consider that almost none of the popular blogs, or social media platforms that we see today will be around in 50 years, it’s hard to imagine what will happen to all the data that these companies would have amassed over the years. The data that would have been chronicles of our life and times.</p><p>When every software we use is a service, then our ownership of things and control over them is dictated by the service provider. In an irony only fitting to the title, in 2009 Amazon <a href="http://www.nytimes.com/2009/07/18/technology/companies/18amazon.html?_r=0">remotely erased</a> all copies of George Orwell’s 1984 from Kindle devices after a dispute with the publisher.</p><p>Gamers feel this often as they deal with their software and hardware becoming incompatible and games being rendered useless, if Steam shut down it’s servers, millions of players will have no rights to play the game which they purchased. If League Of Legends servers shut down, gamers may never be able to play the game ever again because the strong copyrights ensure that the game servers cannot be recreated. Player’s of Crysis and BattleField 1942 realized this when the titles suddenly became unplayable as <a href="https://www.wired.com/2014/06/gamespy-server-shutdown/">GameSpy shut it’s servers</a>. PS3 games are not compatible with PS2 consoles and as support for the software and hardware wanes, any records of the hours of your life you spent playing the game will be gone forever.</p><p>A letter may survive hidden inside a closet for a hundred years, but as time passes and a file format and all it’s related knowledge becomes obsolete, no correspondence or journal written in the file format can ever be retrieved..</p><h3>A brief history of data storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*MHDlP2CFPwe4X7g5_aHrrg.png" /><figcaption><strong>The earliest recording in tablets have survived for thousands of years. </strong><a href="https://www.archaeology.org/issues/214-features/"><strong>Source</strong></a><strong>.</strong></figcaption></figure><p>Our earliest ancestors sketched their thoughts in paintings deep inside caves which turned into timeless archives of data guiding humankind forward. When we started to write, we used to write on clay tablet’s which survived for thousands of years and more and more of them are still being found today.</p><p>Then in the year 1440 AD, the <a href="http://www.bbc.com/news/the-reporters-38892687">Gutenburg Printing Press</a> came along and was one of the defining moments in history allowing people to get access to knowledge that was for so long reserved for the elite, spurring the scientific revolutions which have come to define the modern world. The paper medium had a flaw though, paper is a weak material and decays easily. It’s only the most well preserved books that we find that are hundreds of years old.</p><p>As we marched on to the information age, and transitioned data storage into a stream of bits stored on servers, we spurred another revolution, the internet.<br>Our achievements lie in the advancements in information theory and machine learning. We record our lives on Twitter and Facebook and Instagram which stores its data in public clouds or data-centers, we chronicle our work on Github and store it on data-centers of these SAAS vendors.</p><h3>How are we losing our data?</h3><p>Before we had data-centers we had libraries. Libraries were tasked with keeping catalogues of books and journals considered to be important from the perspective of humanity from the present and the past. These libraries would sometimes survive through centuries, but many of them were destroyed over the years through wars and natural disasters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*Cgs1lZ2OUaMlg7FF9gkkZQ.jpeg" /><figcaption><strong>The records of books and texts we have lost through history</strong></figcaption></figure><p><strong>Changing hardware standards</strong></p><p>The <a href="https://en.wikipedia.org/wiki/Moore%27s_law">Moore’s law</a> states that the number of transistors in an integrated-circuit roughly doubles every two years. Disk-storage and processor power is continually evolving and not always in a backward-compatible way. Often times maintaining backward compatibility simply isn’t possible and other times such efforts are abandoned due to diminishing returns over time.</p><p>We are already losing many films and recordings from the pre-VCR era because people simply forgot to transfer the works into newer storage media and the existing works were lost or the format to play them are not supported anymore. To see how disk storage has changed through the years you can check out this <a href="https://www.pcworld.com/article/127105/article.html">link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*UY2DDsAj0iPob7PKONtu2g.png" /><figcaption><strong>A snapshot of storage hardware through time</strong></figcaption></figure><p><strong>Evolving Database APIs and engines</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*JDyrwe4KWjyszkMyNsiK6w.png" /><figcaption>A snapshot of database API evolution [<a href="https://www.analyticsvidhya.com/blog/2014/11/types-databases-evolution/">source</a>]</figcaption></figure><p>Database APIs have evolved with the changing nature of data, in the earliest days of computing relational databases where hierarchical, until the the Entity-Relationship model was proposed and resulted in the evolution of the relational database management system. NoSQL systems evolved to serve the data needs in the internet era of unstructured data .</p><p>The problem is these APIs are often not compatible with each other . Even variants of SQL provided by different vendors are not drop-in replacements, there are different variants of APIs supported by different vendors and petabytes of data stored in a format which is not compatible with any other API. So if the company backing the API goes out of business, database drivers for popular programming languages will disappear, the data locked in the API will be lost forever even if it has not been actually deleted from the hardware.</p><p><strong>Hardware Failures and Human Errors</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*D8e_OdKbwuwW8SVkVJp4cQ.png" /><figcaption>Predictable reasons for data loss[<a href="http://www.datlabsdatarecovery.co.uk/common-data-loss-situations/">Source</a>]</figcaption></figure><p>Storage hardware often fails, sometimes due to virus or software crashes, other times due to human errors or power outages. Data is lost when your phone hard-drive gets fried, sometimes because it can’t be recovered other times because it may be expensive to do it.</p><h3>The public cloud: A timeless abstraction of the infrastructure layer (In theory at-least)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5zFFjz_0x8KFEUDk1d8Dw.png" /><figcaption><strong>The promise of Timeless abstraction over infrastructure layer transcending hardware or API upgrades</strong></figcaption></figure><p>We trust that the cloud provider will be timeless and will outlast the market forces and changing technologies and that data stored in the public cloud will be etched forever. We believe that the cloud provider will internally migrate the data to newer boxes if the older ones become obsolete. The cloud provider will maintain replicas and copies against data outages and deal with software migration. But perhaps that is simply not true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*3aTQmru3jQUhvsHCJIxt6w.jpeg" /><figcaption>Growth rate for public cloud providers in 2016 [<a href="https://www.channele2e.com/news/gartner-public-cloud-iaas-market-share-amazon-aws-microsoft-azure-google-growth/">source</a>]</figcaption></figure><p>Looking at the global IAAS Market we see many names and start-ups providing “Infrastructure As A Service” solutions. In some sense they will gain and lose market share and with time many names will disappear and new ones will come to take their place and while we may assume that consolidation will happen as giants absorb the smaller ones, we do not know what SLAs will be honored in time with evolving technologies and market-forces.</p><h3>The idea behind YugaByte</h3><h4>A timeless storage engine, agnostic of Infrastructure or API.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNkOINNmg_tic_QSgw4ZeA.jpeg" /><figcaption>We gave names to the stars and constellations and passed it down the generations.</figcaption></figure><p>Yuga represents <a href="https://en.wikipedia.org/wiki/Yuga">an era</a> in Sanskrit. The vision behind <a href="https://www.yugabyte.com/">YugaByte</a> is to build a data layer that is in some sense timeless and indestructible. A few of the founders having built the storage and messaging infrastructure at Facebook and Oracle, uniquely know some of the challenges that companies of tomorrow will face when the scale of petabytes becomes commonplace. The mission-critical data of today will become of the warehouse data of tomorrow and archived data in a few years. We want data to live through changing APIs and hardware specs.We were driven by the following guiding principles-</p><h4>The data layer must be API agnostic.</h4><p>A look into the database systems over the past 40 years shows a landscape littered with APIs none of which are compatible with each other. We set out to build a database that is wire-compatible with Redis, CQL and SQL APIs and is equally performant in most use-cases and more performant in focused use-cases than the original storage engine.</p><h4>The data layer must be hardware agnostic.</h4><p>Can we completely abstract out the infrastructure layer, provide the same experience on AWS, GCP, or OnPrem providers and eliminate cloud lock-in on the data layer.(I believe kids these days are calling it cloud-native)<br>Can we add or remove nodes to the data cluster in a hardware agnostic way, Can we use modern devops tooling and containerization to build a solution that completely abstracts out the infrastructure of the IAAS provider.</p><h4>The data layer must be open-source and compatible with open standards.</h4><p>An open-source code base and a thriving community of contributors means that the software will outlast most market-forces and evolve to support use-cases which are more fitting to the unknown future.</p><h4><strong>The data layer must be distributed and fault-tolerant.</strong></h4><p>Can the data layer tolerate the failure of an arbitrary number of nodes, can we integrate alerting mechanism and metrics natively into the engine so that there is no loss of data due to nodes being down or disks being full. Can we eliminate most ops use-cases for node failure within the orchestration layer itself.</p><h4>The data layer must natively support async replicas and snapshots.</h4><p>Can we apply the principles above not just to the primary cluster but also to read replicas, backups and snapshots and make them hardware and API agnostic too in a sense providing perfect mobility between various infrastructure providers.</p><p>To answer some of these questions, we built the <a href="https://github.com/YugaByte/yugabyte-db">YugaByte project</a>. It is a continually evolving effort towards achieving data that is in some sense permanent.</p><p>If you liked the story, theres 50 ways (claps) to show your appreciation :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><h4>This story is published in <a href="https://medium.com/swlh">The Startup</a>, Medium’s largest entrepreneurship publication followed by 293,189+ people.</h4><h4>Subscribe to receive <a href="http://growthsupply.com/the-startup-newsletter/">our top stories here</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gfnVvkMRFtjVsWF7vkClA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=260a54fef86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-moment-for-all-of-our-data-lost-in-time-260a54fef86">All the data we lost to incompatible APIs.</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>