<?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[Development at Canopy Tax - Medium]]></title>
        <description><![CDATA[Our amazing software is made possible because of our ridiculously talented tech team. Check out their latest work and see how you can join the best talent in the state. - Medium]]></description>
        <link>https://medium.com/canopy-tax?source=rss----b302cd90fbdc---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Development at Canopy Tax - Medium</title>
            <link>https://medium.com/canopy-tax?source=rss----b302cd90fbdc---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:12:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/canopy-tax" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Asyncio Basics in Python]]></title>
            <link>https://medium.com/canopy-tax/asyncio-basics-in-python-29bf30cf254f?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/29bf30cf254f</guid>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Skyler Lewis]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 17:22:56 GMT</pubDate>
            <atom:updated>2024-02-23T19:47:15.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fFgqJ3EQ3Y-YmPf4sVww5g.jpeg" /><figcaption>Concurrently a unicorn and a person.</figcaption></figure><p>Python 3.5 brought with it asyncio, and is part of the standard library. There are other async libraries out there, but I am going to focus on the one built in to Python.</p><h3>Creating an event loop</h3><pre>import asyncio<br><br>async def some_func():<br>  print(&quot;Done sleeping&quot;)<br>  await asyncio.sleep(1)<br>  print(&quot;Done sleeping&quot;)<br><br>asyncio.run(some_func())</pre><p>This is the basic example to get you up and running. This is the core of asyncio. Starting an event loop and running some function on top of it. Some frameworks abstract this from you and handle it on the bootstrap of the application layer (fastapi, for example).</p><h3>The async function</h3><pre>async def some_func():<br>  print(&quot;Done sleeping&quot;)<br>  await asyncio.sleep(1)<br>  print(&quot;Done sleeping&quot;)</pre><p>An async function is like defining a regular function, except we add the async keyword before def. This not only let&#39;s you know the function is asynchronous, but it also let&#39;s the interpreter know that it’s a <em>special</em> function called a <a href="https://docs.python.org/3/library/asyncio-task.html#coroutines">coroutine</a>.</p><p>In our first example we started an event loop and ran our function inside asyncio.run() That will run your function until all synchronous and non-synchronous calls are complete. I like to think of this step as an instantiation of our asynchronous paradigm.</p><h3>The real magic — await</h3><p>Let’s add a new async function and rename some_func to run since that is all we are going to have it do -- run our async logic.</p><pre>import asyncio<br><br>async def speak():<br>  print(&quot;Hey!&quot;)<br><br>async def run():<br>  await speak()<br><br>asyncio.run(run())</pre><p>await tells our event loop to pause here and wait for the coroutine to finish work before continuing on.</p><p>If you do not await the function, then the function will run in series, and the event loop will not yield time to another coroutine. If your function is a coroutine (starts with async def) then not calling await on your function will give you an runtime warning:</p><pre>coroutine &#39;speak&#39; was never awaited</pre><h3>Starting a function and getting back to it later.</h3><p>The first thing you might need an async pattern for is starting a job in the background, do other tasks in the front and then coming back to your original task.</p><pre>import asyncio<br><br>async def my_async_func():<br>    print(&quot;B&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;C&quot;)<br><br>async def run():<br>    async_func = my_async_func()<br>    print(&quot;A&quot;)<br>    await async_func<br><br>asyncio.run(run())</pre><p>If you run this you will see the results:</p><pre>A<br>B<br>C</pre><p>That’s what we wanted right? Close. We wanted to start our async job my_async_func()and when it was done, return the results. However, the first thing we printed to our terminal was A not C. We did not actually start our job, we just defined it. We started it’s execution later when we called await my_aysnc_func. To start the job running while we move on to other tasks, we need to use asyncio.create_task().</p><pre>import asyncio<br><br>async def my_async_func():<br>    print(&quot;B&quot;)<br>    await asyncio.sleep(1)<br>    print(&quot;C&quot;)<br><br>async def run():<br>    async_func = asyncio.create_task(my_async_func())<br>    await asyncio.sleep(0)<br>    print(&quot;A&quot;)<br>    await async_func<br><br>asyncio.run(run())</pre><p>Note: I added a 0 second sleep immediately after we did create_task(). In order for our async_func task to run, we must yield the event loop, allowing the event loop to schedule the task to begin work.</p><ol><li>We make our coroutine a task</li><li>we call asyncio.sleep(0) to pause execution on run() and hop over to my_async_func</li><li>inside my_async_func we print “B”.</li><li>The function will continue to do any other work until we hit the next await statement where it yields back to run().</li><li>In run it then prints “A”.</li><li>It then hits await async_func where it yields back to my_async_func to print “C”</li></ol><p>This should result in the following output:</p><pre>B<br>A<br>C</pre><h3>Order mucking</h3><pre>import asyncio<br><br>async def my_async_func(letter):<br>    print(letter)<br><br>async def run():<br>    # We assign our coroutines to variables<br>    a = my_async_func(&quot;a&quot;)<br>    b = my_async_func(&quot;b&quot;)<br>    c = my_async_func(&quot;c&quot;)<br>    d = my_async_func(&quot;d&quot;)<br><br>    # Then we can execute then in any order we wish<br>    await c<br>    await b<br>    await d<br>    await a<br><br>asyncio.run(run())</pre><p>This will return:</p><pre>c<br>b<br>d<br>a</pre><p>In the above example, I am showing that you can define your work in any order. Then await them out of order. Or in order. Or out of order and then back in order. Or any combination. Great. They all run sequentially though in the order they are awaited.</p><h3>Concurrent runnings</h3><pre>import asyncio<br><br>async def my_async_func(i):<br>    print(&quot;Starting:&quot;, i)<br>    await asyncio.sleep(1)<br>    print(&quot;Ending:&quot;, i)<br><br><br>async def run():<br>    tasks = []<br>    for i in range(3):<br>        tasks.append(asyncio.create_task(my_async_func(i)))<br>    await asyncio.wait(tasks)<br><br>asyncio.run(run())</pre><p>Returns:</p><pre>Starting: 0<br>Starting: 1<br>Starting: 2<br>Ending: 0<br>Ending: 1<br>Ending: 2</pre><p>Here we are creating a list and then adding all of our items to said list. Then we use wait to execute our tasks concurrently. Don&#39;t forget to await the asyncio.wait(). The asyncio.wait function requires your coroutines to be wrapped in a task.</p><p>What if we want to do something with the results of the functions?</p><h4>Handling async function results</h4><p>Our previous example handles the concurrency beautifully. But what if you want to do something with the results of those functions, a la “scatter-gather”? Use gather()!</p><pre>import asyncio<br><br>async def my_async_func(i):<br>    print(&quot;Starting:&quot;, i)<br>    await asyncio.sleep(1)<br>    print(&quot;Ending:&quot;, i)<br>    return (i + 1) * 2  # the first i is a 0, which is why we add 1<br><br><br>async def run():<br>    tasks = []<br>    for i in range(3):<br>        tasks.append(asyncio.create_task(my_async_func(i)))<br>    r = await asyncio.gather(*tasks)<br>    print(&quot;Do something with the results:&quot;, sum(r)) # sum is just an example of doing something with the results.<br><br>asyncio.run(run())</pre><p>This returns:</p><pre>Starting: 0<br>Starting: 1<br>Starting: 2<br>Ending: 0<br>Ending: 1<br>Ending: 2<br>Do something with the results: 12</pre><h3>Update (03–31–18): Blocking the loop</h3><p>One of the most frustrating things you will run into is blocking the event loop. This happens when using a non async function or library. For example if you use requests (non-async as of this update) it will block the event loop, halting all execution until the http call completes and produces a result. Other things that might block the event loop: time.sleep() If you need a non-blocking sleep use asyncio.sleep() Http requests, use a library like aiohttp for async requesting. AMQP, aioamqp is a great alternative to Pika. Last example, Databases. Postgres users I recommend asyncpg and asyncpgsa.</p><p>Example of blocking the event loop.</p><pre>import asyncio<br>import time<br>async def bark():<br>    await asyncio.sleep(3)<br>    time.sleep(3)  # This here is the culprit<br>async def speak():<br>    await bark()<br>    return True<br><br>async def run():<br>    r = [speak() for x in range(10)]<br>    await asyncio.wait(r)<br>loop = asyncio.get_event_loop()<br>loop.run_until_complete(run())</pre><p>If we were to profile the above example in Pycharm, you can see that the first 3 seconds all jobs run at the same. Then we hit a blocking call, and each task is forced to wait until the previous jobs sleep finishes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgve6BpP_7fTnvkf0lJiAA.png" /></figure><h3>Update (12–04–18): Unblock the Blockers</h3><p>I ran into a situation recently where I was using a library that was synchronous. This threw a wrench into how I had designed my worker service. Now, instead of being able to run many jobs simultaneously, all jobs stopped to wait for my synchronous code to run.</p><p>loop.run_in_executor() allows you to take a non async function and put it into an executor, without getting technical makes a sync function async. Take the following code for example:</p><pre>import asyncio<br>import time<br>from concurrent.futures import ThreadPoolExecutor<br><br># This is the blocking function you want to run<br>def blocking_function():<br>    print(&quot;Start blocking&quot;)<br>    time.sleep(5)  # This is the blocking operation<br>    print(&quot;End blocking&quot;)<br><br># An async wrapper to run the blocking function in a separate thread<br>async def run_blocking_function():<br>    loop = asyncio.get_running_loop()<br>    # Run in a default ThreadPoolExecutor<br>    await loop.run_in_executor(None, blocking_function)<br><br># Main function to run async tasks<br>async def main():<br>    # Running the blocking function without blocking the event loop<br>    await run_blocking_function()<br><br># Run the main function<br>asyncio.run(main())</pre><p>In this example, loop.run_in_executor(None, blocking_function) runs the blocking function in a separate thread. By passing None as the first argument, it uses the default ThreadPoolExecutor. This approach allows the rest of your asyncio program to continue running asynchronously, even while waiting for the blocking operation to complete.</p><p><em>Skyler Lewis makes no claims to expertise or exactness of the information presented and may not reflect the opinions of the owners or advertisers. Parental guidance isn’t recommended. Any rebroadcast, retransmission, or account of this article, without the express written consent of Major League Baseball, is not prohibited. Use as directed. May cause sleepiness, headaches, backaches, or thoughts of bacon wrapped shrimp.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29bf30cf254f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/asyncio-basics-in-python-29bf30cf254f">Asyncio Basics in Python</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sammy’s Generators in Python]]></title>
            <link>https://medium.com/canopy-tax/sammys-generators-in-python-57e43386b89e?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/57e43386b89e</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[softwar]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Skyler Lewis]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 17:21:39 GMT</pubDate>
            <atom:updated>2024-03-06T15:48:52.713Z</atom:updated>
            <content:encoded><![CDATA[<p>Python generators are versatile tools that offer unique capabilities for managing data flow and optimizing code efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2660tdL4N-YsCCd8wb-sYg.jpeg" /></figure><p>Imagine it’s lunchtime, and Sammy Sandwiches’ food truck pulls into the parking lot next to your office. A line quickly forms as people eagerly await their favorite sandwiches.</p><pre>import time<br><br># Function to get customers and their orders<br>def get_customers():<br>    return [(&#39;Bob&#39;, &#39;Ham Sandwich&#39;), (&#39;Paul&#39;, &#39;Grilled Cheese&#39;), (&#39;Sally&#39;, &#39;Chicken Croissant&#39;)]<br><br>customers = get_customers()<br><br># Function to make sandwiches for each customer and deliver them<br>def make_sandwiches():<br>    completed_sandwiches = []<br>    for customer in customers:<br>        time.sleep(1)  # Time taken to make the sandwich<br>        completed_sandwiches.append((customer[0], customer[1]))<br>    return completed_sandwiches<br><br>sandwiches = make_sandwiches()<br><br># Deliver the sandwiches<br>for sandwich in sandwiches:<br>    print(&#39;Delivering sandwich:&#39;, sandwich[1], &#39;for&#39;, sandwich[0])</pre><p>Initially, Sammy’s workflow involved taking all the orders first, preparing the sandwiches, and then delivering them. However, as his food truck gained popularity, the long wait times left customers hungry.</p><p>To improve efficiency, Sammy decides to alter his approach. He starts taking orders and delivering sandwiches as soon as they are ready, reducing wait times significantly.</p><pre>import time<br><br># Function to make sandwiches for each customer and deliver them immediately<br>def make_sandwiches():<br>    for customer in customers:<br>        time.sleep(1)  # Time taken to make the sandwich<br>        # Now we will &quot;hand off&quot; the sandwhich<br>        # to the next customer before starting to make the next one.<br>        yield (customer[0], customer[1]) <br><br>sandwiches = make_sandwiches()<br><br># Deliver the sandwiches<br>for sandwich in sandwiches:<br>    print(&#39;Delivering sandwich:&#39;, sandwich[1], &#39;for&#39;, sandwich[0])</pre><p>While this method improves efficiency, it still doesn’t address the issue of customers having to wait for others to order before receiving their food.</p><p>Sammy’s final solution is to take one order, prepare the sandwich, and deliver it before moving on to the next customer.</p><pre>import time<br><br># Function to make sandwiches for each customer and deliver them immediately<br>def make_sandwiches():<br>    for customer in get_next_customer():<br>        time.sleep(1)  # Time taken to make the sandwich<br>        yield (customer[0], customer[1])<br><br># Function to yield the next customer in the queue<br>def get_next_customer():<br>    list_of_customers = [(&#39;Bob&#39;, &#39;Ham Sandwich&#39;), (&#39;Paul&#39;, &#39;Grilled Cheese&#39;), (&#39;Sally&#39;, &#39;Chicken Croissant&#39;)]<br>    for an_order in list_of_customers:<br>        yield an_order<br><br>sandwiches = make_sandwiches()<br><br># Deliver the sandwiches<br>for sandwich in sandwiches:<br>    print(&#39;Delivering sandwich:&#39;, sandwich[1], &#39;for&#39;, sandwich[0])</pre><p>By understanding and optimizing his operation, Sammy achieves success. Generators, like the ones used in Sammy’s sandwich-making process, help streamline workflows and remove bottlenecks.</p><p>Generators not only pause execution to extract values but also allow sending values to the yielding function. This can be demonstrated with the following example:</p><pre>def make_sandwich():<br>    customer = yield &#39;No Customer&#39;<br>    print(customer)<br><br>action = make_sandwich()<br>print(next(action))<br>print(action.send(13))</pre><p>Running the above example produces ‘No Customer’ followed by 13, showcasing the communication between the generator and the caller.</p><p>Another useful feature of generators is pipelining, which allows for cleaner, more readable code. Instead of manually iterating over multiple generators, the yield from statement can be used:</p><pre>def retrieve_all_users():<br>    yield from employees()<br>    yield from customers()<br><br>for user in retrieve_all_users():<br>    print(user)</pre><p>Generators form the basis of many optimizations, including Asyncio, making them essential tools in Python development.</p><p>These adjustments aim to enhance clarity and readability while maintaining the informative content of your article. Let me know if you need further clarification or have any specific questions!</p><p><em>Skyler Lewis makes no claims to expertise or exactness of the information presented and may not reflect the opinions of the owners or advertisers. Parental guidance isn’t recommended. Any rebroadcast, retransmission, or account of this article, without the express written consent of Major League Baseball, is not prohibited. Use as directed. May cause sleepiness, headaches, backaches, or thoughts of bacon wrapped shrimp.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57e43386b89e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/sammys-generators-in-python-57e43386b89e">Sammy’s Generators in Python</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single-spa parcels, explained]]></title>
            <link>https://medium.com/canopy-tax/single-spa-parcels-explained-e225f2b72f71?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/e225f2b72f71</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[single-spa]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <dc:creator><![CDATA[Joel Denning]]></dc:creator>
            <pubDate>Tue, 19 Jun 2018 17:53:13 GMT</pubDate>
            <atom:updated>2018-06-19T17:53:12.984Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever since <a href="https://github.com/CanopyTax/single-spa">single-spa</a>@1.0.0, the single-spa team has been dedicated to <a href="https://medium.com/canopy-tax/a-step-by-step-guide-to-single-spa-abbbcb1bedc6">bringing microservices to the frontend</a>. We have made it possible for AngularJS, React, Angular, Vue, and other frameworks to <a href="https://single-spa.surge.sh/">coexist side by side</a> in the same page.</p><p>And with the release of <a href="https://github.com/CanopyTax/single-spa/releases/tag/v4.0.0">version 4</a>, I’m pleased to announce that <a href="https://github.com/CanopyTax/single-spa">single-spa</a> is expanding that effort so that <strong><em>individual components</em></strong> written with different frameworks can interoperate. It is new terrain for the single-spa community, which previously had focused on getting large applications to interoperate with each other, instead of the individual components.</p><h3>Another way to do framework agnostic components?</h3><p>For those familiar with <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">web components</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements">custom elements</a>, you may be wondering why a javascript library would try to do what browsers are starting natively to do.</p><p>And as one of the contributors to the custom elements polyfill, let me be the first one to say that we did not make this decision lightly.</p><p>If you’re interested in diving into the details, check out <a href="https://medium.com/canopy-tax/one-companys-relationship-with-custom-elements-d360baf3b253">One Company’s Relationship With Custom Elements</a>, which explains some of the difficulties we’ve been through with web components and custom elements.</p><p>TLDR: React and some other frameworks don’t interop with custom elements very well. Additionally dealing with inner html, attributes vs. properties, and customized builtins can be a pain.</p><h3>Okay, but you haven’t told me what a single-spa parcel is.</h3><p>A parcel is single-spa’s way of building a component in one framework and using it in another.</p><p>To implement a parcel, just create a javascript object that has 3–4 functions on it. We call this javascript object a <em>parcel config</em> and there are three required functions to implement: bootstrap, mount, and unmount. A fourth function, update, is optional.</p><p>Each of the functions will be called by single-spa at the right time, but the parcel config will control what happens. In other words, single-spa controls the “when,” but the parcel config controls the “what” and the “how.”</p><p>Once you’ve implemented the parcel config, simply call singleSpa.mountRootParcel(parcelConfig, parcelProps) to mount it. This is the key to what makes parcels framework agnostic — regardless of whether the parcel config is implemented with React, Angular, Vue, or anything else, to use the parcel you always just call mountRootParcel().</p><h3>A few more specifics</h3><p>We’ve glossed over a few things that I want to touch on real quick:</p><ul><li><strong>How do you implement the life cycle functions on the parcel config?</strong></li></ul><p>Use a helper library for your framework of choice. <a href="https://github.com/CanopyTax/single-spa-react">single-spa-react</a>, <a href="https://github.com/CanopyTax/single-spa-angular2">single-spa-angular2</a> (for angular@2+), <a href="https://github.com/CanopyTax/single-spa-angular1">single-spa-angular1</a>, <a href="https://github.com/CanopyTax/single-spa-vue">single-spa-vue</a>, and <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/single-spa-ecosystem.md">others</a> will implement the entire parcel config for you.</p><ul><li><strong>What are the props you pass to </strong><strong>mountRootParcel()?</strong></li></ul><p>The props passed as the second argument to singleSpa.mountRootParcel(parcelConfig, parcelProps) are an object with one required prop and as many custom props as you’d like. The required prop is domElement, which tells the parcel where to mount. And the custom props get passed through to the parcel config lifecycle functions.</p><ul><li><strong>How do you re-render and unmount a parcel?</strong></li></ul><p>The singleSpa.mountRootParcel() function returns a parcel object that lets you re-render and unmount the parcel whenever you’d like to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2d981b380b937009f7ce84e1cc2d753/href">https://medium.com/media/b2d981b380b937009f7ce84e1cc2d753/href</a></iframe><h3>Syntactic sugar makes this easier</h3><p>Calling all of those functions manually might get annoying. So let’s make it easier. Here’s an example of some syntactic sugar for React. Similar features will be added soon for Angular, Vue, and other frameworks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b5904d3423359cb2eef410f9ee35648/href">https://medium.com/media/9b5904d3423359cb2eef410f9ee35648/href</a></iframe><h3>How hard is it to try this out?</h3><p>You can get started with parcels immediately, without using the rest of single-spa. To do so, either npm install or script tag single-spa, then call mountRootParcel with your first parcel config.</p><p>You can also check out <a href="https://codepen.io/joeldenning/pen/qKVoQg?editors=0010#0">this codepen example</a> to start out.</p><p>And if you are already a user of <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/applications.md">single-spa applications</a>, parcels mean that your applications can mount and unmount shared functionality whenever you want them to. Since parcels don’t have <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/single-spa-config.md#activity-function">activity functions</a>, you don’t have to set up routes for them.</p><h3>Let us know what you think!</h3><p>We’d love to get your feedback on parcels. What do you think of this new way of framework interop? Is the implementation easy to understand? Are parcels useful for you, or do they not quite fit into what you’re trying to accomplish?How hard was it for you to try out?</p><p>Check out the <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/parcels.md">official docs</a> for more examples, explanations, and <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/parcel-api.md">api documentation</a>.</p><p>And let us know your thoughts in the <a href="https://join.slack.com/t/single-spa/shared_invite/enQtMzIwMTcxNTU3ODQyLTM1Y2U1OWMzNTNjOWYyZDBlMDJhN2VkYzk3MDI2NzQ2Nzg0MzMzNjVhNWE2YjVhMTcxNjFkOWYzMjllMmUxMjk">single-spa Slack channel</a>, a <a href="https://github.com/CanopyTax/single-spa/issues">Github issue</a>, or <a href="https://twitter.com/Single_spa">on Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e225f2b72f71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/single-spa-parcels-explained-e225f2b72f71">Single-spa parcels, explained</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One company’s relationship with custom elements]]></title>
            <link>https://medium.com/canopy-tax/one-companys-relationship-with-custom-elements-d360baf3b253?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/d360baf3b253</guid>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Joel Denning]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 18:08:20 GMT</pubDate>
            <atom:updated>2018-02-06T18:08:19.629Z</atom:updated>
            <content:encoded><![CDATA[<p>At <a href="http://www.canopytax.com/">Canopy</a>, our journey with <a href="https://medium.com/dev-channel/the-case-for-custom-elements-part-1-65d807b4b439">custom elements</a> resembles a teen drama whose main characters finally got together and graduated high school, but now it’s up for renewal and the writers don’t know where to take it.</p><p>It has all of the elements of that story:</p><ul><li>One side ignores the other</li><li>A chance encounter sparks something exciting</li><li>Infatuation and full commitment</li><li>Rejection</li><li>Even more rejection</li><li>Success</li><li>Hard, painful realities</li><li>Uncertain future</li></ul><p>This blogpost takes you through those phases, including unbending webkits, exciting software conferences, rejected pull requests, forked polyfills, underwhelming transformation layers, painfully brittle tests, and enduring through all of it.</p><h3>One side ignores the other</h3><p>The story starts in 2015 with <a href="https://twitter.com/little_bret">my coworker Bret</a> indoctrinating me with anti-Polymer and anti-web-component sentiment. “You have to interact with them through an imperative API,” he said. “There’s a global registry and you can’t control how you name them!”</p><p>Even still, another coworker, <a href="https://twitter.com/kentmclean">Kent</a>, went forward and dabbled with web components in late 2015. But he ran into cross-browser compatibility issues with the polyfill code itself. So we gave up on web components. They found their way into what-we-hate-at-Canopy lore.</p><p>The type of thing you smirk at with your friends when they come around the corner of the high school hallway.</p><h3>A chance encounter sparks something exciting</h3><p>Fast forward to the 2016 UtahJS conference. Bret attended <a href="http://slides.com/corybrown/native-web-components-now#/">a conference talk</a> by <a href="https://twitter.com/uniqname">Cory Brown</a> who peeled back the layers of polymer, web components, and custom elements.</p><p>We discovered that web components were actually made up of <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">four separate specs</a> and that we didn’t have to use all parts of that spec. You can have reusable, framework-agnostic components via <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements">custom elements</a>, without using <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM">shadow dom</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/HTML_Imports">html imports</a> (which are <a href="https://hacks.mozilla.org/2015/06/the-state-of-web-components/">now dead</a> in favor is ESM imports), or <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots">html templates</a>.</p><p>Cory also recommended using custom elements for leaf node components to start out with, instead of as a full blown UI framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*n0S9QDHh4LgmRzoSeJvt3A.jpeg" /><figcaption>Actual footage of Bret Little</figcaption></figure><h4>This excited us.</h4><p>Bret and I were completely unaware of custom elements existing separately from web components. A lowish-level api for reusable components was exactly what we were looking for.</p><p>We had a mixture of AngularJS and React in a single page application, all coexisting via <a href="https://github.com/CanopyTax/single-spa">single-spa</a> and <a href="https://github.com/CanopyTax/sofe">sofe</a>. Our company styleguide was a combination of raw css and some javascript components — the css was reusable across AngularJS and React, but the javascript components had to be reimplemented in each framework.</p><p>Maybe custom elements could solve all of this for us. We could build leaf node components like buttons, inputs, and multiselects as custom elements to be reused by AngularJS, React, or anything else.</p><h3>Infatuation and full commitment</h3><p>What really sealed the deal, was when I stumbled across the <a href="https://www.w3.org/TR/custom-elements/">custom elements spec</a> and <a href="http://robdodson.me/interoperable-custom-elements/">Rob Dodson’s Custom Elements Anywhere article</a> in fall 2016.</p><p>I was exposed to concepts like <a href="https://www.w3.org/TR/custom-elements/#custom-elements-autonomous-example">autonomous custom elements</a> that had their own &lt;tag-name /&gt; and <a href="https://www.w3.org/TR/custom-elements/#custom-elements-customized-builtin-example">customized built-in elements</a> which extended native elements with things like &lt;button is=&quot;my-button&quot; /&gt;. Both of those sounded perfect for different styleguide components at Canopy.</p><p>I immediately started planning how we could get custom elements into our styleguide. I found out that Chrome (mostly) supported custom elements and that the <a href="https://github.com/webcomponents/custom-elements">custom elements polyfill</a> brought browser support to everything else.</p><p>Like any good teen romance, I committed fully to the idea and was ready to overcome anything to make it happen. No red flag, no matter how serious, would stop me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*HW13sgR7kXB0ke3OeuRTeA.png" /></figure><p>However, <em>there were</em> a few red flags:</p><p>One was that my scrollbar gets really small when I read about <a href="https://github.com/w3c/webcomponents/issues/509#issuecomment-233419167">the controversy</a> surrounding customized builtin elements. Especially <a href="https://github.com/w3c/webcomponents/issues/509#issuecomment-233419167">when a Webkit (Safari) developer says that they will not implement this portion of the spec and that they only approved the spec so that they could try to block it later</a>. 47 downvotes and some toxic flame wars should have deterred me, but I was unperturbed.</p><p>Another red flag was that framework support for interacting with custom elements is <a href="https://custom-elements-everywhere.com/">unfortunately limited</a>. Even modern frameworks like React struggle to allow developers to control whether data is passed down as html attributes or javascript properties. Passing data back up via DOM events has even sketchier support (think refs instead of jsx).</p><p>Finally, writing code for a custom element is unfamiliar, more low level than framework components, and something my team did not have experience in.</p><p>But none of this phased me.</p><h3>Rejection</h3><p>Sometimes in a relationship, it seems like the harder you try the less you succeed.</p><p>I was determined to make all of this custom elements stuff work. I realized the custom elements polyfill didn’t support customized builtins, so I took it upon myself to <a href="https://github.com/webcomponents/custom-elements/pull/42">pull request the polyfill</a>. In January 2017, I made twelve commits over a two week period that brought support for customized builtins to the polyfill. Community feedback was helpful and positive, but I didn’t hear back from a maintainer until March.</p><p>The news was bad. The maintainer explained that the polyfill owners were in the process of rewriting the polyfill from the ground up and that my code would not be merged. He was kind and told me the news regrettably, but I was back to square one. My code would not be merged and I would have to rewrite it.</p><p>Not to be deterred, I re-implemented customized builtins for the rewritten polyfill. Three weeks and eight big commits later, at the end of March, I succeeded in doing so. I opened my <a href="https://github.com/webcomponents/custom-elements/pull/88/commits">second pull request</a>, with hopes high.</p><p>However, that pull request has been drowned out in 76 comments whose content varies from how to implement it, whether to implement it, frustration at the maintainers not being responsive, frustration at lack of unanimity, and also some sprinkled-in productive conversation.</p><p>I did not know what to do, so I asked the twitterverse how to best navigate the politics of web standards:</p><h3>Joel Denning on Twitter</h3><p>Should a polyfill implement something that is in a spec, but which may never be implemented by a particular browser?</p><p>A couple of months later, I took to desperation:</p><h3>Joel Denning on Twitter</h3><p>@BedeOverend @justinfagnani @ebidel @notwaldorf At this point (5ish months of working on it and waiting) I&#39;m basically fine with any sort of changes so long as it gets merged in</p><p>Only the next day to be feeling optimistic:</p><h3>Joel Denning on Twitter</h3><p>Hopefully close to some progress on customized builtin elements pull request for custom elements polyfill! https://t.co/1VJLKaACO7</p><p>Finally, at the end of June, I reached an understanding with the maintainers on an implementation of customized builtins that would be merged and published.</p><p>However, that implementation is pretty tough. It requires patching the polyfill to only support customized builtins via an extra script tag. I do not know how to start such an implementation, since observing DOM changes to call custom element lifecycle methods is something that only the first script should do and would be hard for the second script to hook into.</p><p>I’m not sure how to pull it off; and, for a while, was frankly burned out by all the seemingly wasted effort.</p><p>The endeavor has stalled from June 2017 to present.</p><h3>Even more rejection</h3><p>But it didn’t stop there.</p><p>In January 2017, I attempted to overcome another hurdle: interop with React, AngularJS, and other frameworks.</p><p>This was not a problem I expected to have. The whole point of custom elements was that they were native to the browser, which means they can be used by any framework. <a href="https://custom-elements-everywhere.com/">Right</a>?</p><p>However, <a href="https://github.com/facebook/react/issues/7249">it</a> <a href="https://github.com/facebook/react/issues/7901">is</a> <a href="https://gist.github.com/treshugart/2fb509a8828adf7fee5245bfa2a54ba7">not</a> <a href="https://developers.google.com/web/fundamentals/web-components/best-practices#attributes-properties">that</a> <a href="https://github.com/facebook/react/issues/11347">simple</a>. Frameworks need to pass data into custom elements, and they can pass things either as html attributes or as javascript properties. On the one hand, html attributes can only be strings, but they make things more readable when you Inspect Element. On the other hand, javascript properties can be strings, numbers, objects, or any data type, but they do not show up in the DOM inspector.</p><p>Currently, <a href="https://reactjs.org/docs/web-components.html#using-web-components-in-react">React’s documentation for web component interop</a> is very incomplete. Discussion in the issue queues taught me that react <em>always</em> passes data down as string html attributes. There is no way to pass other data types to custom elements, without using refs. And if you want to get data back from the custom elements (usually done via custom events fired on the dom node), you’re stuck with refs as well.</p><p>And using refs for every button and input sounded awful.</p><p>So I discussed the problem in <a href="https://github.com/facebook/react/issues/7901#issuecomment-256755466">this ongoing github issue</a> until I thought a consensus had been reached. <a href="https://twitter.com/sebmarkbage">Sebastian Markbage</a> was the React core team member leading the discussion. <a href="https://github.com/facebook/react/pull/8755">I pull requested React</a> with a solution for attributes vs properties.</p><p>For (probably good) reasons, my pull request was rejected.</p><p>I wasn’t sure where to go from there — using refs for every custom element was inhibitive. Not having polyfill support for customized builtin elements was discouraging. Not to mention that writing a custom element at all was turning out to be challenging.</p><p>Things were not going well.</p><h3>Success</h3><p>But, with enough effort, we made progress:</p><ul><li>To solve our customized builtins problem, I decided to publish my fork of the custom elements polyfill to npm (yarn add @joeldenning/customelements). We have been using it in production for over six months with no major bugs.</li><li>For React interop, I wrote a <a href="https://canopy.githost.io/front-end/blue/canopy-styleguide/blob/master/src/custom-elements/react-interop.js">generic wrapper around custom elements</a> that allowed us to use custom elements without refs.</li><li>Unfortunately, React itself had a bug that prevented the use of customized builtin-elements at all (even with refs). This was due to a change in the custom element spec before the <a href="https://github.com/webcomponents/custom-elements/releases/tag/v1.0.0">1.0 release</a>. So I put together <a href="https://github.com/facebook/react/pull/9313">a fix</a> that was merged and published in React 16.</li><li>For AngularJS interop, I wrote <a href="https://gist.github.com/joeldenning/7d391770baa2b738bdda179433154937">a directive</a> with limited, but maybe-easy-to-use custom elements support.</li><li>For actually implementing the custom elements themselves, I wrote <a href="https://canopy.githost.io/front-end/blue/canopy-styleguide/blob/master/src/custom-elements/preact-to-custom-element.js">some code</a> to transform preact components into custom elements. The idea was that our team, which already had expertise in React, wouldn’t have to learn all the nitty gritties when writing a custom element.</li><li>We set up <a href="https://canopy.githost.io/front-end/blue/canopy-styleguide/-/jobs/68722">automated, cross-browser tests</a> (via saucelabs) that allow us to test the custom elements in IE11, Safari, Edge, Chrome, and Firefox.</li></ul><p>All of this was launched to customers in about March 2017 and has been working fine!</p><h3>Cold, hard realities</h3><p>But, alas, the honeymoon phase of a relationship inevitably ends.</p><p>It turns out that even after all my work, there is still a pretty steep learning curve for our developers to write their own custom elements. You know things are getting complex when you have to write <a href="https://canopy.githost.io/front-end/blue/canopy-styleguide/tree/master/src/custom-elements">a wiki explaining why things are so damn complicated</a>.</p><p>And even that is not enough.</p><p>Our team still struggles to grok everything and get it all working together. Our preact to custom element transformation is not seamless and we still have to deal with weird things.</p><p>For example, passing “children” to a custom element is very murky. Should the children be created as dom elements inside of the custom element? If so, what happens if the custom element wants to create some children elements of its own? Will that throw off React’s reconciliation algorithm because there are DOM nodes popping up that React didn’t create?</p><p>Another example is that <a href="https://preactjs.com/">Preact</a> might not be the best fit for writing custom elements. The render function on Preact components is meant for creating and updating dom elements, but when writing a custom element you many times are only updating the dom element without creating it. Because of this, the render method of many of our Preact custom elements returns null and only makes updates to the custom elements in the other lifecycle methods. All of this is sort of a weird pattern that isn’t very natural for React/Preact developers.</p><p>Also, we had to resort to setTimeout(() =&gt; {...}, 50) in our testing code. The problem is that the custom elements polyfill doesn’t (or, at least, didn’t) provide a way to know when the polyfill was finished doing all the custom element things. So if you do customButtonElement.actionType = &#39;flat&#39;, there is no way to know in your tests when the custom element has had proper time to respond to the change and update the button to be a flat button. Throw in some socket connections from your build server to SauceLabs and you’ve got some gnarly race conditions. Waiting 50ms is the best workaround we have right now.</p><p>Finally, just last week, I found yet another bug with React, related to customized builtin elements that extend native input elements. This completely prevents &lt;input&gt; from being extended via &lt;input is=&quot;my-input&quot; /&gt; . I haven’t even taken the time to report this one to the React team yet, but hope to do so in the next week or so.</p><p>All of these pains, along with a few others, have consistently popped up.</p><h3>Uncertain future</h3><h4><em>So what now?</em></h4><p>As a company that wishes to have a polyglot of javascript frameworks that all follow a consistent styleguide, it is hard to know what to do.</p><p>Maybe in the next few months, I’ll revive my efforts to bring customized builtins to the official polyfill. And maybe we’ll swap out our preact-to-custom-element layer for something with a community behind it, like <a href="https://github.com/skatejs/skatejs">SkateJS</a>.</p><h4>Or maybe not?</h4><p>Although trying to reinvigorate life into the polyfill pull request would be cool, <a href="https://github.com/joeldenning/custom-elements">our forked version</a> is already working for us. The initial work was a tremendous amount of effort, but now we have it. So there’s not much urgency to move back to the official version.</p><p>Additionally, the ongoing maintenance for our preact-to-custom-elements thing is not overwhelming. It’s not ideal, but it <em>is</em> working for us.</p><p>Or another option could be to ditch custom elements altogether in favor of something easier. However, I don’t know of any such thing — custom elements are the most common answer to the “share components across frameworks” problem. Maybe <a href="https://github.com/CanopyTax/single-spa/pull/160">single-spa parcels</a>?? Exciting, but maybe too unproven and drinking-our-own-kool-aid to bet on.</p><h4>Conclusion</h4><p>So I think you get the picture…<em>we don’t know</em> <em>where Canopy will end up</em>. The teen drama is ongoing and open ended.</p><p>We have tried hard, and the results are mixed.</p><p>We’ll stick with custom elements as long as we find it useful and worth it. And perhaps one day custom elements will be second nature for the javascript world. Or maybe Canopy’s experience is representative of how things have been for years with custom elements, and how they might be for years to come.</p><p>It is impossible to know, but will be exciting to find out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d360baf3b253" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/one-companys-relationship-with-custom-elements-d360baf3b253">One company’s relationship with custom elements</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A step-by-step guide to single-spa]]></title>
            <link>https://medium.com/canopy-tax/a-step-by-step-guide-to-single-spa-abbbcb1bedc6?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/abbbcb1bedc6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Joel Denning]]></dc:creator>
            <pubDate>Fri, 26 Jan 2018 18:37:34 GMT</pubDate>
            <atom:updated>2018-01-26T18:37:50.748Z</atom:updated>
            <content:encoded><![CDATA[<p>Running Angular 1, React, Angular 2, and Vue.js side by side sounds pretty cool. And it seems appealing to have multiple applications coexisting on the same page, each lazily loaded.</p><p>But using <a href="https://github.com/CanopyTax/single-spa">single-spa</a> for the first time can be tricky because you’ll come across terms like “application lifecycles”, “root application”, “loading function”, “child application”, and “activity function.”</p><p>This blog post will take you through setting things up and what choices you have when using single-spa. It’s based on what I’ve seen at Canopy Tax where we went from an Angular 1 monolith to an Angular 1, React, and Svelte polyglot.</p><p>If you’d like to jump straight to a fully working, self contained code example, check out <a href="https://github.com/joeldenning/simple-single-spa-webpack-example">this webpack single-spa starter project</a>.</p><h3>Step One: choose a module loader.</h3><p>Your module loader / bundler is the library you’ll use to lazy load code. I recommend either Webpack or JSPM, if you’re starting from scratch.</p><p>If you go with Webpack, try to use Webpack 2 if you can, since it has <a href="https://webpack.js.org/guides/migrating/#code-splitting-with-es2015">support for promise-based lazy loading</a>. This will make things easier for you later on, since single-spa requires that your <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md#loading-function">loading functions</a> return promises. If you can’t use Webpack 2, getting single-spa to lazy load your code with Webpack 1 will require some boilerplate code.</p><p>JSPM/SystemJS has worse documentation than Webpack, but is a great solution for module loading if you can get past that. I recommend using jspm@0.17 — it’s still in beta but has been worked on for over a year and at Canopy we find it stable enough to use in production.</p><p>If you’re struggling to decide between the two, then ask yourself the following: Do I want multiple completely separate bundles? If you don’t, I recommend Webpack because it has better docs, a larger community, and fewer gotchas. Otherwise, I’d go with JSPM, since Webpack has no plans to support dynamic runtime loading (See tweet below from Mr. Larkin, himself).</p><h3>Sean T. Larkin on Twitter</h3><p>@Joelbdenning @dan_abramov indeed!! It&#39;s a static bundler! Module loading is something we won&#39;t do :)</p><h3>Step Two: create a brand new html file</h3><p>The next step is to create what single-spa calls your “<a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md">root application</a>.” Really your root application is just the stuff that initializes single-spa, and it starts with an html file.</p><p>Even if you’ve got an existing project that already has it’s own html file, I recommend starting fresh with a new html file. That way, there is a clear distinction between what is in your root application (shared between all apps) and what is in a child application (not shared with everything).</p><p>You’ll want to keep your root application as small as possible, since it’s sort of the master controller of everything and could become a bottleneck. You don’t want to be constantly changing <em>both</em> the root application <em>and</em> the child applications.</p><p>So for now, just have a &lt;script&gt; to a single javascript file (root-application.js), which will be explained in Step Three.</p><p>Since Webpack is probably the more common use case, my code examples from here on will assume that you’re using Webpack 2. The equivalent Webpack 1 or JSPM code has all the same concepts and only some minor code differences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f56dbb563c509c43a68f667f24ba0008/href">https://medium.com/media/f56dbb563c509c43a68f667f24ba0008/href</a></iframe><h3>Step Three: register a “child application”</h3><p>Now it’s time to finish up your root application by writing your “root-application.js” file. The primary purpose of root-application.js is to call <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md#declaring-child-applications">singleSpa.declareChildApplication(..)</a> for each of the applications that will be managed by single-spa.</p><p>If you’re into analogies, you can think of single-spa as the operating system for your single page application, managing which “processes” (or “child applications”) are running at any given time. At any moment, some of the child applications will be active on the DOM and others will not. As the user navigates throughout the app, some applications will be unmounting from the DOM and others will be mounting to the DOM.</p><p>Another way to look at it is that single-spa is a master router on top of your other routers.</p><p>To do this, first npm install single-spa and then call the <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md#declaring-child-applications">declareChildApplication</a> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2947b79ccce8d8298c07799b17c4acbf/href">https://medium.com/media/2947b79ccce8d8298c07799b17c4acbf/href</a></iframe><p>Because single-spa is <em>so very</em> cool, we’ve created an app called “cool-app” that will be lazy loaded and mounted to the DOM whenever the url hash starts with #/cool.</p><p>The loadCoolApp function is what single-spa calls a <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md#loading-function">loading function</a>. Inside of it, the import introduces a code splitting point — Webpack will create separate code chunks that will be lazy loaded by single-spa.</p><p>For your specific project, you probably won’t have a hash prefix of “cool”, but I recommend establishing some kind of convention that makes it easy to determine which apps are active. This will simplify the maintenance of your <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/root-application.md#activity-function">activity functions</a>, as you add more and more child applications.</p><p>If you’re going to start out with just one child application, then it might make sense to implement the activity function as() =&gt; true. You can worry about getting fancier once you have more than one application.</p><p>The last thing is to call start(). This is something you <strong>must do for things to work. </strong>The purpose is to give control over timing and performance. But until that is a concern, start is just one of those things you do, and then maybe <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/single-spa-api.md#start">read about it</a> later if you ever need to.</p><h3>Step Four: create “.app.js” file</h3><p>When you open up your index.html file in the browser, you’ll now see….. a blank screen! We’re really close, but there’s one crucial step left: building your app.js file.</p><p>After that, you’ll have everything working for your first single-spa application.</p><p>An app.js file is a configuration file that you create for each child application. It is the code that is lazy loaded when your activity function returns true.</p><p>There are three things that you need to implement in the app.js file:</p><ol><li>A <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/child-applications.md#bootstrap">bootstrap lifecycle</a></li><li>A <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/child-applications.md#mount">mount lifecycle</a></li><li>An <a href="https://github.com/CanopyTax/single-spa/blob/master/docs/child-applications.md#unmount">unmount lifecycle</a></li></ol><p>A “lifecycle” is a function or array of functions that will be called by single-spa; you export these from the app.js file. Each function must return a Promise so that single-spa knows when it is completed.</p><p>Here is a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed8069f6f0e7a89bc6f0af4ae724ab5b/href">https://medium.com/media/ed8069f6f0e7a89bc6f0af4ae724ab5b/href</a></iframe><p>At this point, you might be seeing the document.getElementById and innerHTML = and worry that you’ve been duped — maybe single-spa is really just a poor excuse for a ui component framework.</p><p>And really, don’t we already have a lot of different ways to write UI components?</p><blockquote>But getting all of those frameworks to work together.</blockquote><p><em>Using multiple frameworks</em> is where single-spa really shines. It is not a ui framework itself, but a framework for using other frameworks.</p><p>Each child application can be written in any framework, so long as it implements application lifecycle functions. Then the mini-apps cooperate to form the entire single page application.</p><p>So going back to our previous example, we could choose to write our “cool.app.js” as an Angular 1 app, and choose something else for future apps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4050cbe174c1d6827091199ba94ce1a9/href">https://medium.com/media/4050cbe174c1d6827091199ba94ce1a9/href</a></iframe><p>In this example, we use a helper library called single-spa-angular1 which abstracts away the specifics of initializing Angular 1 apps. This blogpost doesn’t show you the app.module.js or routes.js files, but you can see an example implementation <a href="https://github.com/CanopyTax/single-spa-examples/tree/master/src/angular1">here</a>.</p><p>The pattern is to call singleSpaAngular1 at the very beginning, which returns bootstrap, mount, and unmount lifecycle functions for you.</p><p>You might notice that this time the lifecycles are exported as arrays of functions instead of just functions — you can choose whichever works best for you.</p><p>The advantage of exporting an array of functions is that you can add in your own custom behavior (like aboutToBootstrap and doneBootstrap) that will run before or after the Angular 1 lifecycles. When you export an array, each item in the array must be a function that returns a promise. Single-spa will wait for each promise to resolve, in order, before calling the next function in the array.</p><p>To learn more about single-spa helper libraries, check out these github projects:</p><ul><li><a href="https://github.com/CanopyTax/single-spa-angular1">single-spa-angular1</a></li><li><a href="https://github.com/CanopyTax/single-spa-react">single-spa-react</a></li><li><a href="https://github.com/CanopyTax/single-spa-angular2">single-spa-angular2</a></li><li><a href="https://github.com/CanopyTax/single-spa-vue">single-spa-vue</a></li><li><a href="https://github.com/CanopyTax/single-spa-svelte">single-spa-svelte</a></li><li><a href="https://github.com/CanopyTax/single-spa-preact">single-spa-preact</a></li></ul><p>You can also see a fully working example of an angular app coexisting with other apps at the <a href="https://github.com/CanopyTax/single-spa-examples">single-spa-examples repo</a> or the <a href="http://single-spa.surge.sh/">live demo</a>.</p><h3>Step Five: test it out!</h3><p>Refresh your page and you should now have a functioning single-spa application!</p><p>Try navigating to a url that your child app is active for (`#/cool`) and then navigating away from it. When you do so, the page will not refresh but you should see your application mount itself to the DOM and then unmount.</p><p>If you run into problems, try to narrow down whether the problem is in the root application or in the child application. Is your root application being executed? Are the declareChildApplication calls being made? Have you called start()? Is there a network request to download the code for your child application? Is your child application&#39;sbootstrap lifecycle being called? What about mount?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*WMFuo-hz-Q31UVbTHAx4lw.png" /></figure><p>It may be helpful to add a navigation menu, so you can verify everything mounts and unmounts to the DOM correctly. If you want to level up your single-spa skills even more, make the navigation menu an entire child application whose activity function is () =&gt; true. An example that does just that is found <a href="https://github.com/CanopyTax/single-spa-examples/blob/master/src/single-spa-examples.js#L3">here</a> and <a href="https://github.com/CanopyTax/single-spa-examples/blob/master/src/navbar/navbar.app.js">here</a>.</p><p>While you are verifying that everything is working, keep in mind that each application goes through five phases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*utKlcxBkDXfQAQR52B0hAA.png" /></figure><h3>Conclusion</h3><p>As you get your feet wet, you’ll probably run into some (hopefully small) hiccups setting things up. When this tutorial is not enough, there are other resources on <a href="https://github.com/CanopyTax/single-spa">Github</a>.</p><p>Single-spa is still a relatively new thing, and we’d love to hear your feedback and questions. We welcome contributions from everyone.</p><p>If you’re excited about the possibilities, feel free to contact me (twitter <a href="https://twitter.com/Joelbdenning">@joelbdenning</a>). And if you are not excited, then still feel free to contact me, but only after you leave some nasty comments :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbbcb1bedc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/a-step-by-step-guide-to-single-spa-abbbcb1bedc6">A step-by-step guide to single-spa</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Canopy is a Unique Place for Software Engineers]]></title>
            <link>https://medium.com/canopy-tax/why-canopy-is-a-unique-place-for-software-engineers-8f10b748cb66?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f10b748cb66</guid>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Bret Little]]></dc:creator>
            <pubDate>Fri, 01 Dec 2017 22:27:22 GMT</pubDate>
            <atom:updated>2017-12-01T22:27:21.752Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*JHXMVfh39xsPLfajwzqX1A.png" /></figure><p>Tech startups in need of engineers are sprouting up all across the Silicon Slopes, but the Canopy engineering team is unique. We have daily standups, full transparency (and we mean <em>full </em>transparency — of financials, roadmaps, etc.), and you’ll never see a stack of technical specs just handed off to an engineer. Our values are reflected in our daily work. Here’s a closer look at what makes the Canopy engineering team so different.</p><h3>We’re Owners</h3><p>Canopy engineers aren’t micromanaged in what they code. Canopy engineers are owners. Throughout the process of building the product, they have a big say in making decisions. From being included in product discussions to receiving customer feedback, our engineering team is more than just a branch for implementation.</p><p>Because each engineer is involved in making decisions, they are given full autonomy and trust. There is no gatekeeper to deployment. Canopy deploys several times a day, and every engineer has the ability to deploy.</p><blockquote>“We have a policy of ‘you build it, you run it.’” -Nick Humrich, DevOps engineer</blockquote><h3>We Collaborate</h3><p>Another great aspect of Canopy is the emphasis on collaboration. Rather than sitting together as one engineering team, our engineers sit in squads of two front-end developers, two back-end developers, a QA engineer, a product designer, and a product manager.</p><blockquote>“We collaborate every day. There is never a day when you come in, put in your headphones, and work alone all day.” -Oli Ikeme, software engineer</blockquote><p>Beyond collaborating with other team members who help build the product, Canopy engineers also feel like they play a part in sales and customer support. No one is siloed (there are literally no cubicles in sight).</p><blockquote>“You can talk to anyone and know what is happening with a project.” -Olga Areshnikova, QA engineer</blockquote><h3>We’re Progressive</h3><p>Our software engineers also have an awesome job from the technology perspective. We stay up to date with the latest technology and push the envelope of innovation. A lot of projects at Canopy are challenging, but our engineering team loves a good challenge and the chance to learn.</p><blockquote>“We’re not stale, and we’re not afraid to explore new things. We have a mentality that if something’s working we want to make it work better.” -Oli Ikeme, software engineer</blockquote><p>Canopy embraces <a href="https://github.com/CanopyTax">open source</a> as a tool for innovation. Several of our engineers have written or contributed to major open source projects. Some of the other technical benefits of being an engineer for Canopy include:</p><ul><li>Cloud-hosted software</li><li>Trunk-based development</li><li>True continuous integration</li><li>No dealing with internationalization (we only write for US tax)</li><li>Feature toggle service (deploy to product but not customers)</li><li>Microservices on the front-end</li><li>Python 3.6 asyncio</li></ul><blockquote>“I don’t know if you could come up with more complex business logic than tax. It’s challenging to build, but I think of that as a positive.” -Bret Little, software engineer</blockquote><h3>We Celebrate</h3><p>Lastly, we have a work hard, play hard policy. Canopy finds as many reasons as possible to celebrate and have fun as a company. For team activities the engineering team has tried virtual reality, waterskiing, and even zip lining.</p><blockquote>“We’re encouraged to celebrate both personal and team wins.” -Skyler Lewis, software engineer &amp; DevOps</blockquote><p>On top of the engineers’ activities, there are plenty of other activities to get involved in no matter what your interests are. Whether you want to try mountain biking, join a writing group, go on photography outings, or participate in an intramural sport, we offer it here at Canopy, and you’ll have people who want to join you. Or you can just come to all the parties and enjoy the good food and company.</p><blockquote>“Opportunities like Canopy don’t come up every day.” -Skyler Lewis, software engineer &amp; DevOps</blockquote><p>Want to hear more from Canopy’s engineers? Check out <a href="https://www.canopytax.com/blog/what-makes-a-great-tech-company-a-canopy-engineers-perspective/">What Makes a Great Tech Company: A Canopy Engineer’s Perspective</a>.</p><p>If you’re interested in applying to Canopy, you can find all open positions <a href="https://www.canopytax.com/careers/">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f10b748cb66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/why-canopy-is-a-unique-place-for-software-engineers-8f10b748cb66">Why Canopy is a Unique Place for Software Engineers</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Case for SOA in the Browser]]></title>
            <link>https://medium.com/canopy-tax/a-case-for-soa-in-the-browser-f777a9f139b2?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/f777a9f139b2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Bret Little]]></dc:creator>
            <pubDate>Thu, 30 Nov 2017 18:35:12 GMT</pubDate>
            <atom:updated>2017-11-30T18:35:11.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWAVbZnuATjOVyWhnTt0YA.png" /></figure><p>So you are a web-developer. You write a lot of JavaScript. You have a large single-page application (SPA) with features to add and bugs to maintain. Over time the application grows in size and complexity. It becomes more difficult to modify one portion of the SPA without breaking another portion.</p><p>The company is growing and you are looking for ways to scale the team and code-base. You add unit tests. You add a linter. You add continuous integration. You modularize the code with ES2015 modules, webpack, and npm. Eventually you even introduce new, independent SPAs with each SPA being owned and deployed by independent squads. Congratulations, you have successfully introduced service-oriented architecture on the front-end, or have you?</p><h4>What is Service-oriented Architecture?</h4><p>The fundamental concept behind service-oriented architecture is a service. A service is an isolated piece of code which can only be interacted with through its API. Unlike a shared library, a service itself can be deployed independently of its consumers. Think of a back-end API. The API is the service and the browser is the consumer. The API is deployed independently of the front-end application. There is also only one deployed version of the API available at a URL.</p><p>Contrast a service to a shared library. A shared library is a piece of code that is bundled and deployed with your code. For example, libraries such as Express, Lodash, and React are all shared libraries included in your application’s distributable. Upgrading a version of a shared library requires a new deployment of that distributable.</p><p>Service-oriented architecture is an approach to building software where the application is composed of many independent and isolated services. Those services are independently deployable, generally non-versioned, and auto discoverable.</p><h4>Why Service-oriented Architecture on the Front-end?</h4><p>The benefits of SOA can be illustrated with this real life example from Canopy. At Canopy we have multiple single page applications. The first application is external to the customers and the second is internal, yet both applications share common functionality. That functionality includes among other things, authentication and error logging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*itLASVdD-5a3fm56hfltYQ.png" /><figcaption>Shared libraries between two separate applications. <strong><em>App 1</em></strong> depends upon shared libs <strong><em>a</em></strong>, <strong><em>b</em></strong>, and <strong><em>c</em></strong>. <strong><em>App 2</em></strong> depends upon only shared libs <strong><em>a</em></strong> and <strong><em>b</em></strong>.</figcaption></figure><p>Overall the design looks good. The code is modularized and shared. The complexities arrive when we start to upgrade the code to different versions. For example, after a short period of time, <strong><em>App 2 </em></strong>(being internal only)<strong><em> </em></strong>is<strong><em> </em></strong>upgraded to a new beta version of the shared lib <strong><em>b</em></strong>. Because the shared <strong><em>a</em></strong> also depends upon <strong><em>b</em></strong> (and we don’t want multiple versions of b bundled) we also create a new version of <strong><em>a</em></strong>. This one change causes a rebuild and deploy of three separate pieces of code: <strong><em>App 2</em></strong> and shared libs <strong><em>a</em></strong> and <strong><em>b</em></strong>. Our dependency structure is no longer quite so simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*T5YHqkoZApSvC32jVS0osw.png" /><figcaption>In reality, a duplicate instance of lib <strong>a</strong> and <strong>b </strong>exist in both apps. Each app does not point to the same instance of the shared libraries, even when they are the same version. This is more noticeable when the shared libraries have separate versions.</figcaption></figure><p>Now imagine a bug in both versions of shared lib <strong><em>b</em></strong>. In order to fix the problem, you will have to republish both versions of <strong><em>a</em></strong> and <strong><em>b </em></strong>as well as <strong><em>c</em></strong>. Also <strong><em>App 1 </em></strong>and <strong><em>App 2</em></strong> will have to be re-deployed. That is five new versions to publish and two apps to redeploy, all to fix one bug. All downstream dependencies have to be redeployed when a single library is changed. This is deploy dependency hell.</p><p>Service oriented architecture avoids these problems in a couple ways. Instead of bundling common dependencies, common code is shared through independent services. Services are not bundled, but rather loaded at run time. This also means that front-end services are not versioned (just like a back-end API). Both <strong><em>App 1 </em></strong>and <strong><em>App 2</em></strong> load the exact same code for a front-end service.</p><h4>Introducing sofe</h4><p>Built upon the new ECMAScript module specification, sofe is a JavaScript library that enables independently deployable JavaScript services to be retrieved at run-time in the browser. Because the new module specification isn’t available within today’s browsers, sofe relies upon <a href="https://github.com/systemjs/systemjs">System.js</a> to load services at run-time.</p><p>You can load a sofe service either with static or asynchronous imports.</p><pre>// Static imports<br>import auth from &#39;auth-service!sofe&#39;;<br>const user = auth.getLoggedInUser();</pre><pre>// Asynchronous imports<br>System.import(&#39;auth-service!sofe&#39;)<br>  .then(auth =&gt; auth.getLoggedInUser());</pre><p>The real power behind sofe is that services are resolved at run-time, making them unversioned. If <strong><em>auth-service </em></strong>is redeployed, it is immediately made available to all upstream dependencies. The above scenario becomes much easier to resolve because there is only <em>one</em> version of each shared library as services. This is powerful because it allows you to deploy once, update everywhere. Also because the code is loaded at run-time, we can also enable developer tools to override what service is loaded into your application. Or in other words, you can test code on production without actually deploying to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*o7IS8yKgYKSDc2w7VpyZFw.png" /><figcaption>The common dependencies are now services that are independent from the application code. Because services are unversioned, the dependency structure is again flat. Each service can individually be deployed and be available to every upstream dependency.</figcaption></figure><p>Obviously not all front-end code should be a service. Services have their own challenges. Specifically your code has to stay backwards compatible. But code can’t always be backwards compatible. Sometimes there needs to be breaking changes. The same problem exists for back-end services. A back-end API has to stay backwards compatible. Breaking changes on the back-end are generally solved by either creating an entirely new (versioned) API or implementing feature toggles within the API itself. The same solution applies to sofe services. An entirely new sofe service can be deployed or feature toggles can exist inside the front-end service. However it is solved, the key point is that services exist outside your application within their own distributable.</p><p>Another potential problem for sofe services is performance. Because they are loaded at run-time, performance can become a concern if you synchronously load too many services during bootstrap. Performance degradation can be mitigated by asynchronously loading larger services after the application bootstraps. Despite these challenges, there are many benefits to services on the front-end. The most exciting thing about sofe is there is now an option for services in the browser. You can decide what should and shouldn’t be a service.</p><p>Getting started with sofe requires only System.js. But to help you get started we have built sofe to work with a variety of technologies, including webpack, Babel, jspm, and the Chrome Developer Tools. Sofe is also actively used in production at Canopy Tax. We would love feedback on sofe and a number of open source projects that have been built around it. As you approach your next front-end project or look to improve your existing app, consider how it might benefit from service oriented architecture.</p><p><em>Read more about how to get started with sofe at </em><a href="https://github.com/CanopyTax/sofe"><em>https://github.com/CanopyTax/sofe</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f777a9f139b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/a-case-for-soa-in-the-browser-f777a9f139b2">A Case for SOA in the Browser</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thoughts on Microservices]]></title>
            <link>https://medium.com/canopy-tax/a-case-for-soa-in-the-browser-8b0a3722b897?source=rss----b302cd90fbdc---4</link>
            <guid isPermaLink="false">https://medium.com/p/8b0a3722b897</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Canopy Tax]]></dc:creator>
            <pubDate>Thu, 30 Nov 2017 17:36:30 GMT</pubDate>
            <atom:updated>2017-11-30T18:34:21.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pK4yxtAdWBO2_yXMWVfRjA.png" /></figure><p>The programming world moves very quickly compared to other industries. Many things come and go and it can often be hard to keep up with the latest trends. More often than not, it makes sense to not follow common trends, as they are untested, and might fade in a couple years anyways. How do we decide which trends to follow and which to pass on? This is a really hard problem, but can often be decided by digging further into the trend. Who is else is doing it? Why? What problems are they trying to solve? What problems are created?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*0tNO_E3pRhjAfyzLpBrKOA.png" /></figure><p>Microservices are one of these trends. They have been quite a hot topic for a few years now. It might make sense to wait for others to vet microservices before adopting them. After all, based on google search trends, microservices seem to be a relatively new thing in the programming world. Despite this, one of the main selling points of microservices is that it’s the pattern many large, trusted companies (such as Google, Amazon, Microsoft, Facebook, Netflix, Spotify, etc.) follow. How do so many companies use microservices if it is so new? Turns out <em>microservices</em> is just a relatively new <strong>term</strong>. The concept of microservices has actually been around for a while, it just never had an official name. Microservices is actually a subset of Service-oriented Architecture (SOA). SOA, has actually been around for quite some time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*QgBCMVr_Ks-gGxsoCUW-LA.png" /></figure><p>SOA, however, has created a bad name for itself due to certain patterns which are now considered anti-pattern, such as the “Enterprise Service Bus”. Thus a term for a specific “style” of SOA has been created, which is now called “microservices”. This brings the question, what exactly <strong>is</strong> a microservice</p><h3>What is a Microservice</h3><p>A microservice architecture is a SOA where each service has a couple restraints imposed upon them.</p><p>1) <strong>Smart endpoints and Dumb pipes</strong>. A microservice should have endpoints that can convert a universal contract into objects. A microservice should own its own logic and form its own responses. This is in contradiction of the Enterprise Service Bus, where the bus itself often handles lots of choreography and transformations. It is important that logic be built into the actual service that it’s for.</p><p>2) <strong>Hard boundaries</strong>. Microservices should always talk to each other using a standard protocol, and never using functions/libraries. This protocol is often HTTP. Microservices should never allow other services to reach into their code without going through the defined contract and protocol.</p><p>3) <strong>Independently Deployable</strong>. A Microservice should be able to be modified, tested, and deployed by itself. If services require lock-steps or deploy together as a bundle, that is not a microservice.</p><p>4) <strong>Separation of Data</strong>. A microservice should own its own data. It should never reach into another service’s database. <strong>A database is not a contract</strong>. If multiple services are sharing a database, these are not microservices.</p><p>These constraints must be kept in order to truly reap the benefits of microservices. To learn more about microservices, feel free to read <a href="https://www.martinfowler.com/articles/microservices.html">Martin Fowlers post</a>, or read the book <a href="https://www.amazon.com/Building-Microservices-Designing-Fine-Grained-Systems/dp/1491950358">Building Microservices by Sam Newman</a></p><h3>Pros and Cons of Microservices</h3><p>Nothing is a silver bullet and that includes Microservices. Microservices are not for everyone. Deciding whether to use microservices or not is about deciding where your priorities lie. The typical comparison for most is Microservices vs Monolith. A monolith is a single deployable app which contains all application code. There is only one code base, only one deployable, and one database (well, unless you’re sharding). A monolith is the exact opposite of a SOA architecture, so it balances the cons of microservices very well. That being said, there might be some models that are in the middle ground between microservice and monolith, but for this article I will compare and contrast the two. For some companies/people, the monolith will be the correct approach. But for Canopy, the answer was Microservices. Here are some of the pros/cons to microservices.</p><h3>Pros</h3><p>1) <strong>No shared code base</strong>. Typically when you use microservices, a microservice is owned by a specific team. When you have multiple code bases, your teams are less likely to step on each other’s toes.</p><p>2) <strong>Limited Blast Zones</strong>. If a team pushes bad code or a service dies, it only affects that portion of the application. On a monolith, any change could potentially bring down the entire system.</p><p>3) <strong>Enforced Boundaries</strong>. In single repo projects, boundaries are often defined, but are very theoretical. Breaking the boundaries by having separate code bases prevents people from creating code that crosses several boundaries. It is just too easy to cross boundaries in a single repo, and when people have deadlines they are likely to cut corners.</p><p>4) <strong>Autonomy</strong>. Conway’s Law says that a software’s architecture will eventually mirror the organization’s communication structure. If you want “small blast zones” you have to create <em>autonomous</em> teams. It is too difficult to create autonomous teams when everyone if working on a single repo. If you go with the monolith you end up getting a very hierarchical structure in your organization, as you need certain people/teams to coordinate everything.</p><p>5) <strong>Independent Scalability</strong>. Some products that your organization delivers simply aren’t used to the same scale as your organization’s major products. Having to worry about large scale for products and features that have small use is troublesome. With Monoliths, every product and feature has to be built for your largest scale, since everything is deployed together.</p><p>6) <strong>Frequent small deployments</strong>. Large projects lead to big deployments. Big deployments lead to lots of lock-steps and process. Process leads to infrequent deployments. Because services are independently deployable, the deployments tend to be smaller and have fewer lock-steps. These attributes of microservices allow you to deploy more frequently. Frequency matters when you want a low turn-around time on fixing bugs/security issues.</p><p>7) <strong>Easier Rewrites</strong>. Because services are smaller, you can rewrite entire services without impacting other areas. In a single repo, rewrites are near impossible without freezing feature development. Sometimes the entire app still needs to be rewritten or changed (i.e. a database change). In these cases, you can change one service at a time, and not have to full freeze feature development.</p><p>8) <strong>Tech Stack agnostic</strong>. Because services are split up with hard boundaries between each service, different tech stacks can be used for different products. Perhaps you’re building a new product and it could be written much faster/easier with a different language/database. In a monolith world, you are locked into your language/product decisions. You pick a framework and stick with it. In a microservices world, however, each service could have its own tech stack. You could even run your own experiments as to which tech stack is working better. If you ever decide you need to move to a new stack across services, you can do it one service at a time.</p><h3>Cons</h3><p>1) <strong>Performance</strong>. Microservices often have to make many remote calls to get data owned by other services. The services called have to go to their own database. What could have been a single database call with lots of joins is now a multi-service, multi-database call.</p><p>2) <strong>Dependency Management</strong>. There are no dependencies on a Monolith. You just deploy it. In Microservices, you could depend on a new api for a service that hasn’t deployed yet. You have to manage those dependencies.</p><p>3) <strong>Tools/Configuration Management</strong>. Because there is more than one service to manage, tools are required to manage services and their configurations. Many new tools will have to enter your stack to manage the full picture. You might want a single place to aggregate all logs, metrics, etc. What used to be a simple log file or sql query is now a tool that must be purchased, built, or used, as well as maintained.</p><p>4) <strong>Operations</strong>. Managing a swarm of duplicate stateless servers is relatively easy. Managing a cluster of services where every server potentially has different configurations and services that run on it is much more of a headache. If services have different stacks, they are not all built the same. Tools are required to manage the operations overhead.</p><p>5) <strong>Transaction Safety</strong>. On a monolith, you can make every request a single transaction. If anything goes wrong anywhere, the whole thing can be rolled back. In a microservice environment, a service could fail after it tells another service to do something. This could cause potential data issues.</p><p>6) <strong>Service Discovery</strong>. Now that there are many services, you need a way for the services to find/talk to each other.</p><p>7) <strong>Backwards Compatibility</strong>. When you deploy everything together, you can easily change things such as an API. The new code calls the new API, and everything is great. In a microservice world, you can’t control other services; your APIs must stay backwards compatible — potentially forever.</p><p>8) <strong>Debugging</strong>. Errors can potentially span many services. It can be hard to know which service an error is really coming from. There is no longer a single stack to debug, and its harder to trace what happens across boundaries.</p><p>9) <strong>Overall Complexity</strong>. A microserviced system is a distributed system. There are a lot more parts, and the system as a whole gets a lot harder to manage and reason about.</p><h3>The answer is… Microservices!</h3><p>At Canopy, we decided to bet on microservices despite its cons. We felt that <strong>Autonomy</strong>, <strong>Limited Blast Zones</strong> and <strong>Frequent Deploys</strong> were the most important things for our company, and it outweighed the cons. We ultimately decided that microservices would be a big buy in cost, but would pay dividends in the long run. Here are some our thoughts on the pros and cons and why we went with the decision we did.</p><ul><li><strong>Autonomy</strong>: Autonomy is very important to Canopy. Nothing good ever comes from micro-managing. We believe that when you empower developers to make their own decisions, they move fast and make better decisions. Sure, at times they might make bad decisions, but as long as we fail fast, then we can learn from it.</li><li><strong>Frequent Deploys</strong>: The best way to be successfully is to make many mistakes and to fail quickly. <em>Ken Robinson</em> said: “If you&#39;re not prepared to be wrong, you&#39;ll never come up with anything original.” At Canopy, if we are going to innovate, we need to be able to fail many times. Ideally we recover from our failures as quickly as possible. In order to do that, we need to have short, frequent deploys. Infrequent deploys will scare us into trying new things.</li><li><strong>Limited Blast Zones</strong>: If we are failing a lot, then we need a way to fail “safely”. Adding blast zones to our app allows us to feel more comfortable failing. If we fail we only affect some things. Customers enjoy when things don’t constantly break. Very few customers use ALL features of the app in the same day.</li><li><strong>Operation Management</strong>: Microservices adds a significant overhead to operations. This could require an entire operations team. Instead, Canopy has decided to help mitigate this issue by building a culture of “You Build It — You Run It”. Developers are essentially responsible for handling the operations of their services.</li><li><strong>Tools/Configuration Management</strong>: Many tools are required to manage the differences between services. This can be mitigated by hiring a DevOps team. A team responsible for helping manage all the configuration and settings of the services by providing tools to help get various tasks done.</li></ul><h3>Conclusion</h3><p>In summary, Canopy has chosen microservices despite the upfront cost and challenges in order to help foster a culture of autonomy and fast-failing. As Canopy is growing really fast, the microservices separation of responsibilities should help us scale as an organization without slowing our rate of innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b0a3722b897" width="1" height="1" alt=""><hr><p><a href="https://medium.com/canopy-tax/a-case-for-soa-in-the-browser-8b0a3722b897">Thoughts on Microservices</a> was originally published in <a href="https://medium.com/canopy-tax">Development at Canopy Tax</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>