<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dave Manton on Medium]]></title>
        <description><![CDATA[Stories by Dave Manton on Medium]]></description>
        <link>https://medium.com/@davemanton?source=rss-b633ba99113a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rjkz7noW1bkQTldzUG9CpQ.jpeg</url>
            <title>Stories by Dave Manton on Medium</title>
            <link>https://medium.com/@davemanton?source=rss-b633ba99113a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 05:13:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davemanton/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How we built our website to go as fast as an output cache]]></title>
            <link>https://medium.com/cutting-code/how-we-built-our-website-to-go-as-fast-as-an-output-cache-4583832b523e?source=rss-b633ba99113a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4583832b523e</guid>
            <category><![CDATA[server-side-rendering]]></category>
            <category><![CDATA[static-site-generation]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dave Manton]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 17:52:45 GMT</pubDate>
            <atom:updated>2022-12-31T12:49:25.338Z</atom:updated>
            <content:encoded><![CDATA[<p>So I’m the architect for a UK eCommerce household brand and we decided to rebuild our website, but here’s the problem - our old website was extremely fast and extremely inflexible because it ran using cached output most of the time. The brief for the new site was to make it flexible and easy to change but make it just as fast</p><p>Completely dynamic, but just as fast as an output cached website<em> </em>- this was going to be a challenge!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*LgYBOgZ5li78te5t.jpg" /></figure><p>As we started to build we knew what our technologies would be, we’re a Microsoft house so dotnet 6.0 was a no brainer for the back end and we decided to back this with document databases. We have a full team of front end devs who’s weapon of choice was React, so again this was going to be our front end - pretty standard stuff</p><h4>Understanding our bottlenecks</h4><p>For those who don’t know eCommerce absolutely relies on server side rendering (SSR) for SEO purposes. This means that if your front end html is generated by React then you’re going to have to run a Node JS service in the back end. Node is fine… but it’s also a pain</p><p>The reason Node is a pain is because it’s single threaded. This means that it effectively only deals with a single request at a time, if you’ve got a bunch of async operations that’s fine as it deals with the next request while waiting for a response. However, if your service is compute heavy e.g. server side rendering html, an instance can only handle one request at a time and all other requests are queued. We can get round this to some extent by scaling instances horizontally (more instances) but as JavaScript isn’t the fastest language it still makes it a bottleneck</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*v0DywPS_zwK-JUsC" /><figcaption>Request traffic jam, source: <a href="https://commons.wikimedia.org/wiki/File:Bogota_Traffic_Jam.JPG">https://commons.wikimedia.org/wiki/File:Bogota_Traffic_Jam.JPG</a></figcaption></figure><p>At the beginning it was hard to know what the actual response time impact of SSR would be but identifying the probability was very important. We did some basic tests and found that calling the rendering service could double our response time or more depending on load. It was already useful having it as a separate service so we could scale it independently but we needed to figure out how we could reduce the amount of rendering we needed to do</p><h4>Moving towards a static site model</h4><p>So we started to form a solution. We didn’t want an output cache like the previous website but we needed to server side render only when required</p><p>Why didn’t we want a cache? Our website is extremely dynamic, it has the largest product range of anyone in our sector in the UK. Any given page can contain references to multiple products, PDP pages cross-sell a range of products for example. We receive and dispatch orders 24/7 which then impacts business decisions. Our business operations cause constant changes such as changes to stock code, changes in prices, promotions - you get the idea</p><p>The key is the website should always reflect the truth, we can’t have a different price on the listing page compared to the product page or if a product goes out of stock it should move down our listings to enable a different product to be presented to the customer. Also we want to enable the business to be dynamic - if they want to make a change we want them to be able to do it now, not when the cache expires</p><p>So we wanted server side rendering but we didn’t always want to render it. Basically we wanted static site generation… on demand</p><p>The basic outline here is to generate html and store it for reuse, just like a static website. For most static sites this is done at deploy time, but we were changing the model - we were going to do this on demand i.e. as a request came in from a user</p><h4>How do we keep a statically generated site dynamic?</h4><p>We’ve already said how dynamic our business operations are and therefore how the site had to reflect that - to make this work we had to know when something had changed and when to regenerate any single page</p><p>As with most modern websites, ours is built with a bunch of supporting microservices. Our platform is event driven and works with message queues, changes from the business generally come through these message queues e.g. stock or price changes. However, the website makes direct http calls to the supporting services such as our product catalogue because it needs that information immediately</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*EY-RSQatPGjdgy2d" /><figcaption>Microservices, source: <a href="https://commons.wikimedia.org/wiki/File:Services4.png">https://commons.wikimedia.org/wiki/File:Services4.png</a></figcaption></figure><p>When looking at knowing when to render the page we realised we could use the response codes of these services to programmatically make this decision. Essentially we were going to ask the services themselves whether content had changed since our last request</p><p>This is possible using eTags (entity tags). Essentially an eTag is generated by the service e.g. product catalogue and it uniquely represents the state of that data as a hash. The service sends that eTag with the response</p><p>When we next send a request, if we’ve got that data stored or cached we can send the associated eTag along with the request - if the data is the same the product catalogue would respond with a “Not Modified” (304) response, if it’s changed then we get the new data with a new eTag and an “Ok” (200) response</p><p>Architecturally this was an extremely important decision. There is no better place to understand whether the data has changed than the source of truth. The product catalogue for example will know exactly which elements to look at to generate the eTag as will any other supporting service without having to go through the motions of generating a full payload</p><p>Also this actually reduces our second bottleneck - internal communications. There are two reasons, the first is that if an eTag is provided the supporting service can make early decisions whether the data is going to be the same - potentially returning early and reducing average response time. The second is the size of the payload data sent over the wire internally - for some of our larger products this could include a significant amount of information e.g. 200 kilobytes, but with a not modified response you’re talking a mere 300 bytes. We have found this significantly cut our internal response time and used fewer resources</p><h4>Putting it all together</h4><p>So how does all of this work anyway? How do we get an output</p><p><em>Scenario 1</em> — A page that hasn’t changed (The fast easy one)</p><ol><li>When a user requests a page for our website we retrieve a data record from storage which represents that page, it includes all the data from all the supporting services with all of the eTags associated</li><li>We then make a request to each required supporting service for the required data along with it’s eTag</li><li>In this case all of the responses return not modified, therefore we know we can return our previously static html so we retrieve and return that</li><li>Not only that, but we return an eTag to the browser so in future we could return a Not Modified response which again can significantly reduce response times and leverage the browser cache for the end user</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*tdHGF9O8YowvlUjp9y6-dA.png" /><figcaption>Scenario 1</figcaption></figure><p>This enables super fast responses from our server side. In the case of a Not Modified response we managed to go quicker than our previous sites output cached html. When we have to return the html we’ve found we were on a par with the output cache — to be fair we’ve also upgraded the general infrastructure and technology behind the site but it’s still an achievement!</p><p><em>Scenario 2</em> — A page that’s data has changed</p><ol><li>Again a user requests a page and again we retrieve the page data record</li><li>Again we request from each required supporting service with it’s eTag</li><li>This time, one or more return an Ok or 200 response including the new payload which means we know something has changed e.g. a stock status or a number of reviews or a cross-sell product price</li><li>We send our new data payload to the rendering service which generates the new html</li><li>We place the data changes and the html onto a background queue to be stored for the next request</li><li>We generate a new eTag for the response and return the page response to the user</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*IRYtVSfGL1jP4ISkU2gBfw.png" /><figcaption>Scenario 2</figcaption></figure><p>So is this much slower? Well no slower than a standard server side rendered site without caching. We find responses still usually occur within 250–500ms on average which is not unreasonable, it just wasn’t good enough compared to the old site</p><p>Step 5 was very important as this presented our 3rd bottleneck. As you can imagine, uncompressed html can get very large so writing this into storage could take a reasonable amount of time. By moving this onto a background queue we can move the time taken out of the request scope and get a response back to the user even quicker</p><h4>Does it work?</h4><p>Yes it works extremely well, that’s why I’m writing about it!</p><p>We’ve managed to build a website where you can change pretty much anything and the changes will be reflected immediately on the site with only a few slightly slower requests (depending on load). What’s also interesting is that as the site comes under more load it becomes faster on average because users are first loading each page for each other, this means that the html is pre-generated for most people and so the site goes quicker overall</p><p>Generally the site works better under a bit of load. Our standard site metrics show an average server side response time of 60–80 ms but of course user mileage will vary when you add network time and payload size into the equation plus we can scale out at any time</p><p>In the graph below you can see our median server page response is 55 ms for this 24 hour period. The median hump is generally when we return previously generated static pages. There’s also a second hump of responses below 220ms which generally represents requests which require regeneration - so it’s still pretty quick</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*9oxgUUgXwGj8u_se5r5Ktw.png" /><figcaption>Example page response time range over 24 hours</figcaption></figure><h4>Isn’t this just a cache?</h4><p>Okay, so we’re calling this static site generation on demand but how is this different to caching really?</p><p>Well first off caching is generally temporary storage and usually based on age. A cache entry will usually age out and need to be replaced at that point as when it ages out it becomes a cache miss which forces regeneration. We’re not aging out our pages, they’re fully persisted and could stay the same indefinitely. Some of our pages are extremely long-lived, consider the contact us page or the FAQ page, they may not change for months or even years</p><p>Secondly there’s how you use a cache - generally speaking a cache is a hit or miss affair. You attempt to hit the cache with a key and you either get something back or you don’t. If you get something back you tend to use it regardless, you don’t tend to calculate whether it should be used - if it shouldn’t be used it should have been a miss!</p><p>What we’re discussing in this article isn’t the same model because we’re not just returning the data we’ve persisted we’re checking it’s validity on every request and then deciding whether it can be used or should be replaced</p><h4>Is it really a static site?</h4><p>I guess not in the purest terms… what we’ve done is layered dynamic request processing over static stored files and you couldn’t just drop this onto a content delivery network (CDN) like a standard statically generated site</p><p>Each request is handled individually and processed but a very high percentage of requests return pre-generated and statically stored html which is where I’m coming from in naming it static site generation on demand</p><p>You can also leverage a CDN with this solution if you’re prepared for and understand the potential pitfalls of external caching. Simply pass a cache control header to your CDN along with the eTag that represents the page. The CDN could store the static output and then re-validate it at the end of the cache period - making it much more like a pure static site</p><p>Anyway, if you’ve got a better name then let me know!</p><p>Thanks for reading, if you’ve found this article useful then please give it a clap and share it around</p><h4>Addendum</h4><p>Someone requested a more formalised flow of the process so I’ve put together a little diagram here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHMC8p1CrWB6bokJi5P_lg.png" /><figcaption>Page request flow</figcaption></figure><p>To create this diagram I used <a href="https://sequencediagram.org/">https://sequencediagram.org/</a> I’d recommend it as a very easy tool for defining request sequences</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4583832b523e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cutting-code/how-we-built-our-website-to-go-as-fast-as-an-output-cache-4583832b523e">How we built our website to go as fast as an output cache</a> was originally published in <a href="https://medium.com/cutting-code">Cutting Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why we need to abstract dependencies, a real world example with react router]]></title>
            <link>https://medium.com/cutting-code/why-we-need-to-abstract-dependencies-a-real-world-example-with-react-router-8b06d1540264?source=rss-b633ba99113a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b06d1540264</guid>
            <category><![CDATA[abstract]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dave Manton]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 17:28:26 GMT</pubDate>
            <atom:updated>2020-11-01T17:28:26.091Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently we found we’d made a bit of a mistake in our code. We’d forgotten to abstract away a dependency and now the package was changing. We were going to be in find and replace fun for a couple of hours and then the testers were going to have the joy of making sure it all worked. This was a lesson for the devs who’d made this micro-site in why we abstract away dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/0*dOg9WpMimCHb8-er.jpg" /></figure><p>So what’s the big deal? Well, like everyone working with React we’ve been going through the learning process of using hooks and building sites while the npm packages we use are also upgrading. In particular when we started building this particular site react-router-dom didn’t have the hooks for useHistory and we ended up using a separate history package ourselves. This was the particular dependency that should have been abstracted away and it would have been pretty easy to do.</p><p>I’m sure most of you know about the history functions in react router, but for those who aren’t in the know let’s cover it off quickly. When navigating between pages in an application you can’t always use links, sometimes you need to perform actions and then navigate so you’d perform your logic and then use history.push({ pathname }). That method will navigate you to your new page.</p><p>Let’s take a look at the problem. If you hadn’t guessed already history had been used throughout our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*DHlk-IOZzJ9sEv9esHCwSw.png" /></figure><p>We’d got 165 usages! Okay, let’s be honest it’s not quite that many once you’ve taken into account modules and json files etc, but it’s still a lot. Why don’t we just use find and replace? Well you can’t, some of those are imports, some are method calls. On top of that we’re going to start using useHistory instead which has a completely different setup because now we’ve got to follow the rules of hooks. Find and replace just isn’t going to cut it.</p><p>C’mon it’s not that big a deal I hear you say… Well now someone has to sit down and think about how to approach this better. When we’ve got a solution, we’ve got to upgrade our entire site. This means someone is going to have to sit down and go through every one of those 165 usages, they’ve got to change the import statements, they’ve got to change the method calls. They’ve got to figure out the weird edge cases where someone did something they shouldn’t have done, they’ve got to figure out if tests need changing depending how they were written. Then a tester has to sit down and depending on how diligent they are test each one of those links to make sure the app still works. Then we’ve got to make sure that any work that’s currently in flight also gets upgraded to use this method as well and communicate the change to everyone.</p><p>… this is, depressingly, going to take a lot more time than it should have done, it’s realistically going to be a day or two of work for a couple of people if doing everything thoroughly.</p><p>So how can we do this better? Well as with all dev work there’s always loads of different ways you can solve a problem. We decided we wanted to abstract away the use of history into a custom hook. What does this abstract away term mean? Well basically you want to put it behind another method/class/ interface (encapsulate it) so that whatever methods use this functionality don’t even need to know it’s there. As we said, we use history to navigate from page to page, so we’re going to create a collection of navigation methods which have the new useHistory hook at their base.</p><p>Okay, let’s take a look at some code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3993f9785f5d7c591e53f569681c94c5/href">https://medium.com/media/3993f9785f5d7c591e53f569681c94c5/href</a></iframe><p>The first thing to notice is that we have a base hook. Basically this is where all the logic is and is a wrapper round the useHistory hook. The problem in our site was the constant use of history throughout the application, I don’t want to make a similar mistake now by restricting history to a single file but still using it many times by putting it in every route. This wrapper creates the functionality which would be used in every single route but so that it only has to be written once.</p><p>The next thing you’ll notice is that the base hook isn’t exported. This is encapsulation, the design here is that devs should create an exported method for each route. Why? Well that means that the route only has to be written once, the routes are also being abstracted away. If I were to export the base hook and spread that throughout my application then if a route changes I have to track down every single usage of that route and update it, I’ve got the same problem all over again just on a smaller scale!</p><p>Okay, so then we’ve got a method per route which is exported. This is what we’ll actually use in our components, the route is defined in here and passed to the base hook which then prepares the navigation function. The hook returns this function which when executed will perform the navigation. Pretty simple stuff, but now the history is restricted to a single place so if we have to upgrade it again, or the signature changes or even if we just want to go back to the old library for some reason then we only have to make a single change.</p><p>Let’s not do that thing where the example is really simple in the blog post and doesn’t work in practice. Let’s push on, what about when you’ve got a dynamic route?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df1862aeac0e96a5ce5f0786a7a23b45/href">https://medium.com/media/df1862aeac0e96a5ce5f0786a7a23b45/href</a></iframe><p>So what’s new? Well now we’ve got a new method called updatePath. We’re going to use a similar way of defining paths as is used in the react-router-dom package where you use a colon for the name of a path parameter. All we’ve got to do is pass in an object of path parameters and we’ll do a find and replace to put the parameters into the path before giving it to the history object. There’s a few different ways of doing this, I went with regex because it’s easy to do find and replace but I also appreciate it’s a little strange removing the colon from the key to get the parameter value, you can change this if you want.</p><p>You can also see in the base hook we’re now not returning the same function, now it’s a function which accepts a parameter. We then extract the path object out of this parameter to send to the createPath method.</p><p>Why have I added an extra path object into the params object? Well that’s because in the next step we’re going to add to this with query parameters as well.</p><p>Why am I not destructuring the object straight away? Well what if I don’t want to use any parameters? On methods where I don’t need to use any dynamic parameters this would force me into passing an object to stop it trying to destructure undefined. The lack of overloading methods in javascript is both a blessing and a curse but this way I don’t have to pass in a parameter if I’m not using one.</p><p>Why am I using lodash get? Well I think it’s pretty useful and reduces the amount of undefined checks I have to do, it’s up to you if you want to use it yourself, but if you do try to minimise your import size.</p><p>One last thing to notice is my useNavigateToUser hook. Notice how I don’t pass on the complexity to the calling method, they don’t know that I need a path object in there. I’m keeping the method signature as simple as possible, they only have to pass in a userId, I’m going to handle what needs to be done for them and encapsulate the inner workings in this collection of hooks.</p><p>Also, I know I only need one parameter here so you might consider using object destructuring to be overkill, but just remember that in other methods there’ll be more parameters and passing an object means they don’t have to get those parameters in the right order. It’s easier to use if the method signature is consistent so making it always an object keeps life simple.</p><p>Great, so now I can create more complex paths. If I put multiple properties into my path then it’ll get extracted from the object keys and put into the path by the functions we’ve created. More importantly this is all abstracted into this single place and I don’t have this code repeating over and over.</p><p>Okay, let’s go one step further, what about query strings? Well hopefully you can guess but it’s just another method to build up the query string, let’s take a look.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1794b915f48846371b61afc0e3fb1a89/href">https://medium.com/media/1794b915f48846371b61afc0e3fb1a89/href</a></iframe><p>Okay, so it’s simply a create query string method. All it’s going to do is create the key value pairs and pass them into the history search object building it up as a query string.</p><p>Why don’t I have a query string in the initial hook setup? Well imho query string parameters are for things which are variable, it doesn’t seem like something you would set up for a fixed initial path. Ideally we shouldn’t be repeating paths multiple times by fixing them in place so leave something which varies to an input parameter.</p><p>Notice again how we’ve encapsulated and hidden away the logic to create the necessary parameters object to pass to the function.</p><p>There we have it. Now we have one place to create all our navigation functions. Is this better?</p><p>Well first up, I’ve only got one place where history is being used now. Once I’ve implemented this then in theory if I need to change that package, or revert back then I only have one file to edit in one place. That’s going to be significantly quicker to work through than when history is spread throughout the entire site!</p><p>It’s also easier for our testers. If all these methods share the same base functionality then I can probably get away with picking a few methods that cover all the scenarios because they all behave the same way and its easy to check. This is the same for unit tests. I can use the same base mock setup for everything and it’s going to be consistent across all these methods now.</p><p>Is it going to be more code? Well I was moving from history to hooks anyway. So in the new class I would need to call the useHistory hook and then perform my history.push action. This is basically exactly the same amount of code but now it’s easier to maintain, because I only have the one place where history is used.</p><p>Can I extend this to use other history functions such as replace and storing browser state? Yes, it’s really easy, just add to this hook, alternatively add other encapsulated methods. You could have a state which if it exists get’s stored before you navigate away. You could implement a flag that tells you to replace instead of push if you want to block someone going back to a page.</p><p>So often it seems like building abstractions like this is just boiler plate and pointless and it’d be much quicker to just reference the library directly especially when you’re under pressure to deliver. But this is a real world example of why this should have been done in the first place, because in the long run this cost us an unnecessarily large amount of time to fix and this one wasn’t even that complex.</p><p>You never know how these dependencies might evolve or if they might even cease to exist at all! When you thread them throughout your application you could be creating yourself a major headache in the future. But if you learn to abstract away and encapsulate those dependencies then you have something much more manageable if one of those changes does occur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b06d1540264" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cutting-code/why-we-need-to-abstract-dependencies-a-real-world-example-with-react-router-8b06d1540264">Why we need to abstract dependencies, a real world example with react router</a> was originally published in <a href="https://medium.com/cutting-code">Cutting Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing a lot of azure service bus topics and subscribers]]></title>
            <link>https://medium.com/cutting-code/managing-a-lot-of-azure-service-bus-topics-and-subscribers-ee16daaff760?source=rss-b633ba99113a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee16daaff760</guid>
            <category><![CDATA[logic-apps]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Dave Manton]]></dc:creator>
            <pubDate>Thu, 29 Oct 2020 10:52:53 GMT</pubDate>
            <atom:updated>2020-10-29T10:52:53.210Z</atom:updated>
            <content:encoded><![CDATA[<p>So recently we had a problem. We’ve started building a micro-service based e-commerce platform that communicates using azure service bus. Unfortunately we found that setting up azure functions with a service bus trigger either ended up with a lot of code to maintain or a lot of deployment pipelines. It was getting to be a pain, so we looked for an alternative which we found with logic apps and a bootstrapper function which I’ll take you through how to implement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*SuaQCQw0jERc_hOq.jpg" /></figure><p>So what’s the problem with Azure functions? I’m not knocking them, I like them and they’ve got a great place in our platform. However, every time we added a topic or subscriber we either had to copy and paste some code, or configure a new deployment pipeline or somewhere in between, but either way it was more dev work than it needed to be. We were finding either a growth in code or a growth in pipelines and it was getting in the way of real work. We needed a way to setup subscribers without additional code and deployments to maintain.</p><p>This alternative turned out to be another Azure function but a function to <em>manage all the resources </em>for our service bus, essentially a service bus bootstrapper. I’d really like to give credit to our principal engineer Paul Milligan for the initial vision for this here, he had a great idea and we worked on this together to come to this final solution. Check out the example we’re going to build on my <a href="https://github.com/davemanton/servicebusbootstrapperexample">github repo</a>.</p><p>How does this work I hear you ask? Well first up you need some data that represents the structure of your message queues so you can start creating your service bus entries. We decided to go for a Cosmos Db; it’s quick and easy to setup a data structure and it’s easy to query the data you need. Alternatively you could use a relational db or even a flat json file if you really wanted to.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce1e15d3848c3b7bbb62ca31fd5573bb/href">https://medium.com/media/ce1e15d3848c3b7bbb62ca31fd5573bb/href</a></iframe><p>Let’s unpack this json then. The type is simple, that’s my cosmos db partition key. For the rest, basically we have a topic with a name we’ll use in service bus and an array of our subscriptions which I can loop through. Obviously we’re going to add to this later, but this is enough for now to bootstrap our service bus.</p><p>So how am I going to handle this in code? I already said I was going to create an azure function, I’m going to assume you can handle this by yourself. I also need to create a service bus instance in azure. At minimum this needs to be on the standard tier but if you have enough topics and subscribers that you need to bootstrap them then that’s probably a given anyway, I reckon you can probably manage to set that up by yourself as well.</p><p>So let’s get to some code, C# is my weapon of choice</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/419f8dd6ec8a665599909265466d1efa/href">https://medium.com/media/419f8dd6ec8a665599909265466d1efa/href</a></iframe><p>Okay, so this should be pretty straightforward. Before we get into the method let’s just check my dependencies. I’ve got a data provider which is querying my cosmos db and then I’ve got a management client for connecting to service bus. The management client comes from a nuget package called Microsoft.Azure.ServiceBus and you’ll need a connection string with management access. You can set up the client and connection string using standard dependency injection patterns in the function startup.</p><p>So what’s happening in the code? Well first of all I’ve got to get my topics and then loop through them all. If a topic doesn’t exist I create it, if it does then I don’t. Then I basically go through the subscriptions with the same logic. The difference there is I have a couple of settings which I reckon are pretty self-explanatory, in reality you’d set this up with some sort of configuration.</p><p>Why have I used async LINQ? When I ran this I found that it could get quite slow at the point of deploying the logic app, so this is prep for later. This Linq means that I’ll kick off all the deployments more or less at once. Remember the aim here is to manage a <em>lot</em> of topics and subscribers and their apps. Each logic app can take over 30 seconds to deploy so doing this synchronously would take a really long time.</p><p>But overall the logic is pretty simple and after running this I end up with the topics and subscriptions created in my service bus and I didn’t have to use a single portal mouse click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDzzmNylRjIfhbXky0wqbA.png" /><figcaption>topic created in service bus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZa5xzngGckKOhCQ0AIVHw.png" /><figcaption>subscriptions created in service bus</figcaption></figure><p>So now we can bootstrap all the subscriptions in service bus, but being honest that’s not the biggest deal, it doesn’t take long to set those up by hand. The problem as we all know is all the subscriber apps. As I said before I didn’t want to have to manage and maintain the code and deployments for many subscriber functions so we’re going to have a look at using logic apps instead and how we can bootstrap them with this function.</p><p>First up let’s look at creating the logic apps. We’re going to do a simple version but you can get more complicated if you want to; In our full setup we’ve built in things like slack notifications for our team on dead letters.</p><p>Step one, (and this is <strong>really important</strong> but you’ll see in greater detail why later) create a specific resource group that’s going to store all your bootstrapped subscriber logic apps and nothing else. I’m going to assume you either know or can work out how to create a resource group.</p><p>On to the logic app. For designing your logic app I have to admit it’s much easier to do in design view, so create an example logic app you can delete later when using the bootstrapper function.</p><p>First up we’ve got to pick a service bus trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*H0C4ypDeVw0R25fFSd65pA.png" /><figcaption>service bus trigger options</figcaption></figure><p>For now we’re using topic subscriptions but you could configure this differently if you wanted to. When working through this I looked into peek-lock vs autocomplete and I decided to go with peek-lock. Here’s why; when you peek-lock you get exclusive access to the message from the logic app and nothing else can access it until the lock expires. You have to manually complete the message which we’ll do at the end of the function, however you’ll definitely know if you’ve completed or not. When using autocomplete the logic app completes the message for you but only on the next visit to the service bus, if you make the logic app trigger infrequently then potentially the lock has expired before your logic app completes the message so something else picks it up. I’m a bit of a control freak anyway, so I want to know for sure that my message has been completed so it’s easier to just put in the steps for my peace of mind.</p><p>When creating your trigger it’ll ask you to create a connection, you might as well set up a connection string at this point, you’re going to need listen permissions. We’ll actually setup the connection differently later but you’re going to end up using the same connection string so you might as well get it done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*KVGJAU6fDQP_pM_e1fIUIg.png" /><figcaption>setup for the service bus trigger</figcaption></figure><p>So I’ve got a trigger set up. This is all pretty self-explanatory but one thing that’s interesting is the frequency which you’ll check for items. Now with a function it’s a push mechanism from the service bus to the function. With the logic app it’s a long polling mechanism, but it’s not as straightforward as it sounds.</p><p>I’ve set this to run every ten seconds. That means it will open a connection to service bus and leave it open for 30 seconds, if there are existing messages or new messages in that time it will take them off the queue and process all of them. Once that 30 second window is over it will wait 10 seconds (my execution frequency) and then repeat. You could narrow this down to 1 second at most if you were so inclined, I guess it depends on the priority of your messages; for some you might want to increase it for others decrease it.</p><p>Now we need to setup what we’re going to do with that message, this completely depends on your setup but we’re running api micro-services on azure app services so I’m going to do an example with an http call for simplicity. You can obviously set it up as you see fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*lyuc5sQc7DiIcHvbSS5rEw.png" /><figcaption>defining the action to perform</figcaption></figure><p>This is pretty straightforward, we’re going to post the content of the message to an endpoint on a micro-service. Don’t forget you need to figure out your own json structure in here or whatever format you choose to post with. You can do what you need to do in terms of authorization (we will discuss this later) but there’s one last thing you do need to know about the content that goes in the body. The content is a base64 string. So you’ve got options, you can either handle that here or you can do it on the service end, for the sake of brevity I’m going to leave that decision with you and just send the base64 in this example.</p><p>Next up, we need to handle the response, so add a control and select condition. It’s going to be pretty simple in this example, if the http call returns a 200 then it was successful, if it doesn’t, it wasn’t.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PW3pcKLBLqicnlkWYiyKnQ.png" /><figcaption>checking for a successful http call</figcaption></figure><p>There is one issue we ran into with this and that was the possibility the endpoint on the other side failed or timed out so you need to add some settings to the condition with the configure run after option in the menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*qE6QXuJFLdSTRpdvFt-MuA.png" /><figcaption>configure run after options</figcaption></figure><p>Just select all the options, because no matter what happens you want to manage this message to some kind of conclusion. This matters because a non-success code being returned from the http call would result in the logic app deeming itself to have failed at that stage, so if you don’t select ‘has failed’ here then you can’t handle that condition which leaves your messages constantly being reprocessed until expiry.</p><p>Okay, so first of all let’s deal with the success condition. It’s pretty straightforward, you want to complete the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*IKPZkrGK6OLxcLdHT-aiPA.png" /><figcaption>completing the message when the http call is successful</figcaption></figure><p>This is all self-explanatory. You can select the lock token from the initial service bus trigger properties. You also don’t need a session id unless you’ve set up your service bus to use sessions, if you have you can probably handle it.</p><p>So what about on failure? Well it’s pretty much the same, but this time we’re going to dead letter the message. If you want to you can put some kind of retry logic in but that’s for you to figure out. In reality, we created a dead letter monitor function that picks up messages off the dead letter queue and schedules a retry on a sliding timescale and then eventually drops them on a poison queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*2EirLyxW30V_MzUoeSg79w.png" /><figcaption>dead letter the message on failure</figcaption></figure><p>I’ve included a really simple failure reason here. In reality we actually return a failure reason in the response with a proper code but this is something I’m sure you can handle.</p><p>Great, so we’ve got our designed logic app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmXmT1p0fQh-ozz_lNlhcw.png" /><figcaption>the full logic app</figcaption></figure><p>Now it’s time to get that into our bootstrapper.</p><p>One of the best things about azure is azure resource manager (ARM) templates. Essentially this is a json document that describes a deployment. So, because a logic app isn’t actually code, this means you can define a parameterised template to deploy. Now with a bit of technical magic know-how you can make that customisable to the configuration in your database.</p><p>Let’s have a look at exporting and editing that template. First off find the button for exporting your template and download it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*PG9iiaM_xn3oGdW9PKip8g.png" /></figure><p>You’ll end up with a zip file with two json files, a template file and a parameters file; we’re only interested in the template file.</p><p>First up let’s think about making this a bit more generic, we’re going to need to parameterise everything in here, so what do we need?</p><p>The bootstrapper is going to create logic apps for you so you’re going to need a logic app name. You’ll need to know where you’re deploying it to so you’ll need a resource group. Service bus stuff is a given so you’ll need a topic and subscriber name, but don’t forget you’ll also need the details of your connection to the service bus. Then finally an url which we’ll contact with the message payload. Great, let’s look at how we inject those into the template json file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f9e7fec73e9ae2b99e54439c6c28712/href">https://medium.com/media/8f9e7fec73e9ae2b99e54439c6c28712/href</a></iframe><p>At the top of the template json file you’ll find there’s a parameters section, basically add a list of parameters like I have above, don’t worry about the values for now because that’s what we’re going to be setting in code. However do be aware of the types, particularly the use of securestring for secrets, make sure your connection strings and other secret data uses the securestring type so they won’t be visible in the actual app.</p><p>Great once we’ve got a list of parameters we now need to set about adding those into the template in place of some of the values.</p><p>Let’s start off with the trigger. Work your way down the template til you find the triggers. In that section you’ll find there is a section called inputs and you’re going to want to change the path so it looks like the below, you’ll also want to customise the recurrence interval. As you can see this will replace those values with our parameters. Great, now we can trigger our logic app for any given topic and subscriber at any frequency interval.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e2a40974ebe5ea4074078d3f58bbf92/href">https://medium.com/media/8e2a40974ebe5ea4074078d3f58bbf92/href</a></iframe><p>Okay, we now need to look at our actions. One thing that’s confusing about this is that they seem to be in reverse order. Don’t worry too much about it just remember you need to start from the bottom up if you’re a stickler for chronology. I reckon you can probably guess what we’re going to do but let’s go through it anyway.</p><p>First of all here’s the http call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37202f03c1fd37e5addae03b5ee69d1c/href">https://medium.com/media/37202f03c1fd37e5addae03b5ee69d1c/href</a></iframe><p>Yep, you guessed it, we replaced the uri with our parameter. Next up comes the conditional actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4547520d2e19a1b6fdf401807a83d703/href">https://medium.com/media/4547520d2e19a1b6fdf401807a83d703/href</a></iframe><p>Yep, not rocket science, I just changed the path on each of the actions to use our parameterised topic name and subscriber name. So what’s left? We need to set up the name, region and service bus connection. So here you may find that your logic app template doesn’t have everything you need. So check out the gist below for how to add in the connection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a210101a20972b4d2072616c1bc7b17d/href">https://medium.com/media/a210101a20972b4d2072616c1bc7b17d/href</a></iframe><p>Awesome, we’ve got a fully parameterised template file. Now we can get to work with a function to automate this deployment!</p><p>We’re almost there, but there’s a couple of things you’re going to need. First of all we’re going to use two nuget packages for creating resources. You’ll need Microsoft.Azure.Management.Fluent and Microsoft.Azure.Management.ResourceManager.Fluent.</p><p>These two nuget packages provide functionality akin to the azure CLI in C# form. With these we can connect to azure to create our resources. However, you can’t just let any old function have the rights to create and delete resources so you’re going to need to set up an app registration in your azure active directory.</p><p>If you remember I said you should create a resource group especially for these logic apps, well that’s because we’re allowing code to create and manage resources, you should <strong>absolutely definitely scope this app registration access </strong>so it only has permissions to manage resources in this one resource group, don’t let it manage your entire subscription! It just takes a small mistake for it to accidentally delete everything! (yes, someone did that with an azure dev ops template and no it wasn’t me or Paul)</p><p>To create your app registration search for app registrations in the portal and create one as usual. Then head to IAMs on the resource group you set for the logic apps and give it contributor access. You’ll need this when you set up the azure client in your dependency injection so check the github repo if you’re not sure what I’m talking about.</p><p>Alright, on to the code! So below we can actually see this is really simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d34adbe5362e08c49ca17a71cf68fd6e/href">https://medium.com/media/d34adbe5362e08c49ca17a71cf68fd6e/href</a></iframe><p>You setup an azure client and some config and read in the template file as a json string in the constructor.</p><p>We need a standard naming convention for the logic apps, you can see I’ve gone for a prefix with topic name and subscriber name, find something that works for you. Be aware though that logic app names can be a maximum of 64 characters long.</p><p>Next we just check if the logic app exists yet, if it doesn’t we create it using the template. Before we finish on this though a really key point is the Deployment Mode (and this is where it can go horribly wrong)</p><p>In the deployment mode you <strong>MUST</strong> select <strong>incremental</strong>. Incremental means that it will either create or update a resource with the selected name. The other option is Complete, this is where you can get in a mess! Complete means that it changes the <strong>ENTIRE RESOURCE GROUP</strong>! So if you’ve only got one resource defined in your template it will delete everything else and replace it with this single resource! Yes it did happen, no it wasn’t me (or Paul).</p><p>Okay, we’re done with this class, all you’ve got left to do is integrate that into the service bus bootstrap code but you can check the <a href="https://github.com/davemanton/servicebusbootstrapperexample">github repo</a> for that.</p><p>If you’re observant you’ll have noticed I’ve added some more data into the cosmos db so now it looks like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9177d4939badcd29d18c64b1525b7db/href">https://medium.com/media/f9177d4939badcd29d18c64b1525b7db/href</a></iframe><p>Okay, so what happens when we run this? Well first up you should find you’ve got two new logic apps appropriately named</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*aeIxhQyd5NR6Za5sNlR-xA.png" /></figure><p>Now you can delete the example one you made. It’s all in the template file so you don’t need it. Next check one which doesn’t match the example you did, so in this case we’ll look at subscriber two and checkout the designer view. I won’t go through every stage but you can see below we’ve deployed with the values from cosmos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*OXS_ePheF_jVagj1mQEfcQ.png" /></figure><p>Great stuff, is there anything else? Yep, you’ll also find it’s setup the connection to the service bus with your connections string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*3eBO8qIErir4TtY2NXFLsw.png" /></figure><p>Now all you’ve got to do is to chuck some messages through it and you should find it all works! Congratulations, you’ve just made managing your service bus subscribers a lot easier! All you’ve got to do now is add records to your database and run your bootstrapper.</p><p>Okay, so are there any other considerations. First of all some of you might be wondering about scale. We put 10,000 messages through a single logic app and found with a frequency interval of a second it could handle around 500 messages a minute. If you need more then one approach is to deploy more logic apps, you can have more than one subscribed to the same topic/subscriber due to the peek-lock functionality.</p><p>What about security? Well it depends on your setup but you may be working with a vnet and logic apps can’t be setup within a vnet which you might think was problematic. One approach is to use a managed identity with your logic app subscribers and include this in the template, then you can secure the resources they contact using azure active directory. You may be thinking that you don’t want to do this with all your internal services which is fair enough but you could use api management if you’ve got it setup or a single function or proxy as an entry point which signposts based on path, there are solutions out there. Alternatively if you’ve got a magic money tree then pay for an isolated environment.</p><p>One last question is whether it’s possible to do this with Azure functions. The answer is yes, and this may solve some security problems as you can then deploy them inside vnets or whatever setup you may have. However it’s considerably more complicated for an already overly long blog post. Essentially it’s the same idea but you also need to deploy some actual code.</p><p>Get stuck in and see what you can do.</p><p><a href="https://github.com/davemanton/servicebusbootstrapperexample">davemanton/servicebusbootstrapperexample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee16daaff760" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cutting-code/managing-a-lot-of-azure-service-bus-topics-and-subscribers-ee16daaff760">Managing a lot of azure service bus topics and subscribers</a> was originally published in <a href="https://medium.com/cutting-code">Cutting Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving Single Page Applications from Azure with Blob Storage (and making it work when you refresh…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/cutting-code/serving-single-page-applications-from-azure-with-blob-storage-and-making-it-work-when-you-refresh-713faf3df387?source=rss-b633ba99113a------2"><img src="https://cdn-images-1.medium.com/max/1280/1*pD7tLTLmhgNSGMpPgh9dRQ.jpeg" width="1280"></a></p><p class="medium-feed-snippet">Azure is great, React is great, but serving a React app or any single page application from Azure is not so great at the moment. It seems&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/cutting-code/serving-single-page-applications-from-azure-with-blob-storage-and-making-it-work-when-you-refresh-713faf3df387?source=rss-b633ba99113a------2">Continue reading on Cutting Code »</a></p></div>]]></description>
            <link>https://medium.com/cutting-code/serving-single-page-applications-from-azure-with-blob-storage-and-making-it-work-when-you-refresh-713faf3df387?source=rss-b633ba99113a------2</link>
            <guid isPermaLink="false">https://medium.com/p/713faf3df387</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Dave Manton]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 20:02:41 GMT</pubDate>
            <atom:updated>2022-12-29T10:57:54.976Z</atom:updated>
        </item>
    </channel>
</rss>