https://www.henrik.org/

Blog

Showing posts with label #Programming. Show all posts
Showing posts with label #Programming. Show all posts

Monday, July 17, 2023

Why I created Underscore Backup

I started running a server for storing all my projects as well as various multimedia artifacts in 1999 with a small desktop computer and a 20GB HDD. As the size and personal importance of this server grew within a few years I started running RAID5 and then RAID6 to make sure data was not lost from single drive failures. Despite this, in 2006 the current incarnation of this server encountered a catastrophic 3-drive failure which I only managed to recover from after a tremendous amount of work and a fair amount of luck which included among other things manually patching the Linux RAID kernel code to remove certain fail-safes as I pulled data off the partially assembled RAID.


"The Server" in its current iteration.

This episode led me to look for ways to safeguard against this ever happening again. Looking through what options were available to me I found Crashplan which did address all my needs at a reasonable price. My initial backup to Crashplan took several years to complete over my 20mbit/s broadband uplink as my server had at this point grown to several TB.

A few years after I started using Crashplan they stopped offering consumer backups and the only way to keep using them was to migrate to their business plan which I did. However, Crashplan only allowed you to migrate a few TB per computer at the time which meant that I had to re-upload most of my backup again. Fortunately, at this point, I had gotten a fiber internet connection with a reasonable uplink that allowed me to re-upload this data in less than a year. As my backup of this server grew Crashplan also started showing its flaws where it required several GB of memory to be able to back up my server, but it did work and allowed me a reasonable peace of mind for the contents of my server.

This went on for a few years after which I was contacted by Crashplan (Now called Code42) and told that unless I reduced the size of my backup to under 10 TB, they would terminate my account since they considered me violating their terms of service by keeping too large a backup.

From: Support Ops (Code42 Small Business Support) 
Date: Feb 6 2020, 10:38 AM CST 

Hello Administrator,

Thank you for being a CrashPlan® for Small Business subscriber. We appreciate the
trust that you have placed in CrashPlan - that relationship is important to us.
Unfortunately, we write to you today to notify you that your account has
accumulated excessive storage, which will result in degraded performance. You 
have one of the largest archives in the history of CrashPlan. It is so large, we
cannot guarantee the performance of our service. Due to the size of your
archive, full restores of your backup archive, and even selectively restoring 
specific files, may not be possible.

As a result, we are notifying you, per our Master Service Agreement and
Documentation, to re-duce your storage utilization for each device to less than
10TB by June 1, 2020. Note that we have extended your subscription to June 1, 
2020 to give you ample time to make changes. If you do not do so by June 1, 
2020, your subscription will not be renewed, and your account will be closed at
the end of your current subscription term.

…

Thank you, 
Eric Wansong, Chief Customer Officer, Code42

The server I was using was Linux based and as far as I could tell Crashplan was the only competitor on the market providing cloud-based backup solutions for that OS. This was when I decided to start working on Underscore Backup as a means for me to continue making backups of my server as I couldn’t find any existing alternatives that fulfilled my needs. The first version was command line only and very primitive even though it did support point-in-time recovery, backup sets as well as obviously efficiently handling my very large backup. Another feature that was built in from the beginning was a strong focus on encrypting everything as much as possible so that any medium could be used for backups even if it was not properly secured from prying eyes. Creating the initial backup of my server using Underscore Backup used a more or less sustained 600mbit/s (To be compared with the at the time impressive 60mbit/s that I experienced using Crashplan on the same connection).

At the same time, I also started using the iDrive service for backing up my laptops and various other smaller Windows and MacOS based machines. I did this because I didn’t think the CLI (Command Line Interface) only implementation of Underscore Backup was just not convenient enough to be used on these machines). This situation continued for a few years when the CLI-only version of Underscore Backup backed up my server data to cloud block storage and my other machines were backed up by the iDrive service. This all came crashing down when my main development laptop of several years had a catastrophic SSD failure and I had to restore my data from iDrive. I found out two things about how the iDrive service works.

The first is that even though iDrive keeps track of versions of your files they do not keep track of directory contents and deletions of files. This is critical to any developer, and I restored a large developer repository with files that I have been working on as I have been running iDrive in the background. For those of you who are not developers, we rename files a lot. And every one of the old names of all my renamed files was restored back when I did a full restore of the contents of my laptop’s hard drive. That meant, that any repository of code that I had basically worked on since I started using iDrive was no longer in a buildable state without a considerable amount of work.

The second surprise to me was that even though to me the iDrive backup of my laptop was relatively small, only around 50GB in size it took almost 2 weeks to restore. Granted it contained a large number of files (Around 3 million, mostly small, files) but I was shocked at the slowness of its performance. I also opened up several support cases with iDrive about this but it was nothing they could do to help me. For comparison, on the same network with roughly the same sized backup in both files and total storage Underscore Backup would complete a similar restore in about 5 minutes (And it would do it properly keeping track of deleted files).

At this point, I evaluated other solutions available but could not find any that would be suitable for my needs. Carbonite does not allow you to specify what files should be backed up but instead in the interest of simplicity tries to be smart about it, when I tried it on my development files it decided to back almost none of them even though I specifically said to include the directory. Backblaze is a very solid solution but also does not keep track of deleted files for a true point-in-time recovery same as iDrive. In the end, I decided that I would put in the effort needed to create an easy-to-use user interface for Underscore Backup so that it would be suitable for use on things other than servers. The end result of these efforts was the first stable release of Underscore Backup in the summer of 2022 and which at that point graduated to be the only backup solution I used on all my computers.

The problem at this point though was that even though I had a backup solution that fulfilled all my needs it was still very tricky to set up for most users since to use it you generally had to supply your own cloud storage such as Amazon S3. It was also quite tricky to access data from other sources you had backed up since every source had to be set up individually on each client you wanted to restore the source on. The sharing functionality, even though present was also so complicated that I am relatively certain nobody managed to set this up except for myself. To solve all of these problems I decided to leave the service-less nature of the software I had followed up until that point and create a service to both remove the need to provide separate cloud storage and also help manage multiple sources and set up shares. This was a relatively large undertaking, but it eventually led to the launch of Underscore Backup 2.0 in the first half of 2023.

This current release as of this writing is the upcoming 2.2 release which has made it very easy to set up backup of multiple computers of any size while staying true to the original guiding principles of security, durability, efficiency, and flexibility.

This post was cross posted from the Underscore Backup blog.

Wednesday, April 26, 2023

Announcing Underscore Backup 2.0 and service general availability

First stable version of Underscore Backup with support for the companion service is now available. The service itself is also generally available.

Even with the new service, the main focus of the application is privacy, resiliency, and efficiency. The new service does significantly simplify setting up cloud backups and sharing though compared to use

The main new feature in version 2.0 is the introduction of a companion service that will help with many aspects of running Underscore Backup such as.

  • Keep all your sources organized in one place to easily restore from any of your backups to any other backup.
  • Help facilitate sharing of backup data with other users.
  • Optionally allow private key password recovery.
  • Easily access application UI even if running in a context where a desktop is unavailable, such as root on Linux.
  • Use as a backup destination. Storing backup data is the only feature that requires a paying subscription, giving you 512GB of backup storage for $5 per month.
  • Support multiple regions of data storage supporting North America (Oregon), EU (Frankfurt), and Southeast Asia (Singapore) regions to satisfy latency and data governance requirements.

On top of the companion service changes, the following features and improvements have also been implemented.

  • Added support for continuous backups by monitoring the filesystem for changes.
  • Introduced a password strength meter which requires a score of at least “ok” when setting up.
  • Switched from pbkdf2 to Argon2 for private key hashing function.

On top of the companion service changes, the following features and improvements have also been implemented. Get started by downloading the client now.

Tuesday, March 7, 2023

Building an online service on a shoestring budget

Photo by Josh Appel on Unsplash
Although I have been working professionally as a software engineer since I was 18 years old I have always had hobby projects I have been working with on the side and I generally take a somewhat perverse pleasure in figuring out how to build and launch these things on as small of a budget as possible. This post is an attempt to go through some of the things I have found that have helped me be productive and successfully build and launch several hobby projects.

I am particularly going to assume that this is for hobby projects and that the skill and time of the participants are free. If you are paying any salary that will dwarf anything you might save by aggressively using free tiers of online services. I am also going to assume your team is small (Less than 5).

What not to skimp on

First, let us go over the things you should not skimp on. The most important thing here is to not use any equipment or software from your day job. The reason for this is that if you do then your employer can usually claim ownership of any IP produced with their equipment. Also check your employment contract to make sure your employer doesn't have a clause to claim ownership to anything you do. That said, if you live in California, even if your employment contract does claim this it is not enforceable as long as you don't use company equipment, time, IP and you are not directly competing with your employer (See labor code 2870 for details).

One more of the things I would advise you to do is to enroll in school if you are not already. Being enrolled in a Community College only costs a few hundred dollars a year and will provide you with free licenses to a huge amount of tools for software development. Telerik, IntelliJ, Autodesk, and many more give students a free non-commercial license to almost their entire catalog of tools and libraries. Granted, once you get to the launch stage you will need to buy real licenses for your tools, but it will still save you tons of money in the development phase. You might even learn something doing it.

Basic development tools

I believe that if code isn't checked into a source repository with change tracking it basically doesn't exist at all. So, the first thing to do when starting a project is to pick a source code repository. GitHub is the giant in the field and they are fantastic. Not only do they give you free private repositories they also give you 2000 minutes a month of build executions (GitHub Actions). If you are building open-source applications you even get unlimited build executions for free.

Next you probably want to choose a cloud provider. I would pick one of either AWS or Azure. If you can go Serverless then I would go with AWS since they have a perpetual free tier for everything you need to launch a Serverless service. If not, then Azure Bizspark is a great program if you qualify. AWS also has a program for $300 to spend getting your prototype ready. Another tip for getting started on AWS is to get a new account for any new project. This is because they have an additional massive free tier that only lasts for 1 year after opening the account. It is also generally best practice to only run 1 microservice per account. Once the freebies are over you can tie your accounts together using AWS Organizations and SSO to help you keep track of them all (Doing this will usually invalidate the free tiers so wait a year after account creation to do this).

You also likely need a web UI testing tool. I use Cypress which has a free tier and is overall very good. They only allow 500 test suites per month so you can't run canaries in the free tier, but it should be sufficient for any deployment-based testing. They also provide a dashboard where you can see which tests have succeeded and failed with videos of the test execution so you can easily troubleshoot failures, something that is very useful when you integrate it into your CI/CD pipeline.

How to build your software

The key thing you want to avoid if you are launching something on the cheap is fixed infrastructure. If possible, use serverless functions instead of hosts or containers to host run your code. With some thought, almost everything you build can be run in a true pay-per-use manner. For instance, with AWS you should aim to use API Gateway, Lambda, SQS, and DynamoDB. As your service scales, you might consider moving off some of these for cost reasons but these primitives are also able to scale to thousands of transactions per second without any change to infrastructure if done right and none of them have a fixed cost. You generally don't want to use services such as Kinesis, Elasticache, Opensearch, relational databases, hosts, or containers since these all come with minimum fixed costs even if your service has no usage.

Useful services with good free tier

Here are a couple of other services worth noting with useful features and good free tiers.

  • Google Analytics is ubiquitous for site analytics. It is having privacy issues in the EU though with several countries declaring it illegal recently. Another option that I use that with more of a privacy focus is Clicky.
  • Also useful from Google is Firebase which provides a lot of features such as a basic user database, usage analytics, and monitoring among others. It is a great choice if your primary use case is a mobile app. It is pretty inflexible for building complex applications or services though and you probably want to go with a normal cloud provider for that.
  • Cloudflare is Web Application Firewall and has a very useful free tier. They also provide a privacy-focused and less annoying CAPTCHA service called Turnstile.
  • Blogger is a free blogging platform. It will generally not let you build your entire website like Wordpress will, but if all you need is blogging it does that well and allows you to use custom domains for free. 
  • Crisp is a great platform for providing support for your site and they have a nice free tier for getting started.
  • Auth0 provides a platform for helping you do auth of your users and has a decent free tier to get you started.
  • Most of the payment processors such as Square, Stripe, and Braintree only charge a percentage with no setup costs. Their fees are very similar, I prefer Stripe myself only because they have fantastic developer documentation.

Launching and running a service

As you first start out I tend to not think too much about schedules and deliverables. The reason for this is that I do this for fun and the best way to kill the fun is to start making yourself a slave to delivery commitments and launch dates. That said as you get closer to launch I really do think you need a way to keep track of remaining tasks and open bugs etc. In my opinion, Jira from Atlassian is by far the best and most comprehensive tool for this and as long as you have a small team everything you need is available for free.

You will need monitoring of your service before you go live. Both AWS and Azure have built-in monitoring tools and they work well. Also worth mentioning again in this space particularly is Firebase which does have some monitoring and analytics capabilities. Another service in this area that has a good free tier is New Relic. One thing that neither AWS nor Azure has is paging for when things actually go wrong. The tool that I found here that has a very functional free tier is Pager Duty, that said you are likely to want to upgrade from the free tier pretty soon as your service takes off to be able to have more control over your escalations.

Your service will likely need a single place to aggregate everything that is going on in one place such as task completions deployments and any issues and here Slack is hard to beat and have a great free tier.

Be frugal, not cheap

As a parting word, I would like to point out that although figuring out how to build and launch your service cheaply don't let that stand in the way of building your service right. Never pick the cheap option over the correct option, you will always regret it in the end.

For me, one of the main reasons why building things in a frugal way when I am working on hobby projects is that it allows me to have fun doing them longer because I don't have the pressure of needing to be done and launched fast because I am bleeding money during the development phase.

Being frugal during the development phase might also allow you to retain a larger portion of your equity if you actually launch your service because it will reduce the amount of help you will need to get started before you get a customer base. As an example, one of my previous projects Your Shared Secret literally has $0 per month of fixed cost. My more recent project Underscore Backup is not quite that cheap but has a fixed cost of less than $50 per month. Most of that cost is for CloudWatch alarms, KMS keys, and Dashboards.

Friday, February 24, 2023

Started another blog

Created another blog at https://www.mauritz.dev for more shorter snippets of what I am working on right now. Really its just something to put on this domain that I've had for a while now without doing anything with it.

Thursday, February 16, 2023

Launching Underscore Backup service and first beta of the version 2.0 of Underscore Backup application to use it

Finally launched the first public release of the Underscore Backup service. A backup service that is a companion to the Underscore Backup application I have now been working on for a few years. I am really excited about this since adding a service component to the application solves a couple of user pain points with my previous releases, such as.

  • Its now easy to coordinate and keep track of multiple sources so you can easily restore data from another computer you are backing up.
  • It comes with the ability to use the service for storage so that you don't have to deal with configuring S3 or something similar. The storage also supports 3 regions in the US, EU and the Asia Pacific region and is priced lower than S3.
  • It makes it easy to set up sharing between users.
  • The service can provide optional secret key recovery.
  • You can easily keep track of where the administration interface of the application is available even if the application is running in a context that does not have access to your desktop.

There is also a ton of other additional features included such as improve password hashing algorithms, log rotation, integrated password strength meter and built in new version notification.

You can head to the site to download the latest version and sign up for the service. The service is entirely free, however you do need a subscription for using storage as detailed on the pricing page.

Tuesday, March 3, 2020

Announcing the first public release of Underscore Backup

The first Underscore Backup pre-release is available for immediate download from Github.
  • Public key based encryption allows continuously running backups that can only be read with a key not available on the server running the backup.
  • Pre-egress encryption means no proprietary data leaves your system in a format where it can be compromised as long as your private key is not compromised.
  • Runs entirely without a service component.
  • Designed from the ground up to manage very large backup sets with multiple TB of data and millions of file in a single repository.
  • Multi-platform support based on Java 8.
  • Low resource requirements, runs efficiently with only 128MB of heap memory.
  • Efficient storage of both large and small file with built in de-duplication of data.
  • Handles backing up large files with small changes in them efficiently.
  • Optional error correction to support unreliable storage destinations.
  • Encryption, error correction and destination IO are plugin based and easily extendable.
  • Currently supports local file and S3 for backup destinations.

Best of all it is available as open source for free under a GPLv3 license.

For now this software is still under heavy development and should not be relied upon to protect production data.

Monday, April 15, 2019

Released Your Shared Secret Service

I recently published Your Shared Secret service which allows you to safely and securely ensure that private information that you have is not lost if you are in any way incapacitated.

The basic premise is that information is submitted through your browser where it is encrypted before it is ever sent to the service. The key to decrypt the information never leaves your browser. The key is then then chopped up into multiple pieces which are securely handed out to a number of people that you chose to act on your behalf and only by a group of them collaborating (You chose how many) can they together assemble the key required to access your information. For a quick introduction you can check out this video.

I really went all out on the privacy aspect of this website and service and have gone out of my way to not collect any information not needed for the operation of the service. The site have no third party links except for when collecting payments and it does not collect any visitor analytics such as for instance Google Analytics.

You have complete control over who of your caretakers is able to initiate accessing the information and also how many of the total group of caretakers need to participate to access the information. Even better the service does not even need know how to contact the caretakers. This information is only known by the unlocking caretaker and the owner of the information.

Furthermore the act of one of your caretakers trying to assemble the key will give you as the creator a notification that allows you to cancel the unlocking information or delete the information all together within a 7 days quarantine period. For more information on how the service works see the Usage section on the website.

The entire service operates on a zero trust model where all the functionality is ensured with cryptographically strong primitives with the single exception being the 7 day quarantine period. There is plenty of detailed information on how the encryption works in detail and how the service has been built. To ensure what is claimed on the site is actually what is happening the source code to the entire service is published on GitHub and you can even run the entire website locally by just cloning the website repository and just run.

npm start

The service is available for an introductory price of $1 or if you want to have completely anonymity you can also pay with either Etherium or Bitcoin although that is slightly more costly because of the value fluctuations of these currencies.

The service is available now so feel free to get started now keeping your information safe without you.

Thursday, December 6, 2018

How to maintain work life balance and sanity in the tech industry

As you collect experience and hopefully get more senior in your position you are at some point undoubtedly going to get to a point where this is something you will need to start thinking about.

I surprisingly often get asked by junior colleagues about how I deal with this, with the implication (At least in my mind) that I seem to have gotten some things right in their eyes so I figured I will try to share some of my insights, tips and tricks in this area.

Work with something you love

This might sound kind of obvious, but also I have found a lot of people don't like what they do. The key here is that you want to work with something that you don't mind doing if you have nothing else going on. The other part of this tip is that when you don't have anything else going on, try to have the discipline to actually work. What this allows you to do is not work when you do have other things you would like to do.

Make sure you also have a boss that realizes that as long as you get your stuff done, it doesn't matter how or when you do it. If this isn't the case for you, start looking for another place to work.

Set boundaries

In my entire life I don't think I have ever worked on a project that had enough time to get everything that we wanted done in the time allotted to do it. With that you have to realize that very few people will tell you to work less, it is up to you to set the boundaries of how much you work. There is also a point of diminishing returns for when the quantity of work put in doesn't actually increase your productive output.

You also shouldn't compare yourself to your colleagues too much, especially when it comes to the quantity of work put in. First of all there have been tons of studies that have concluded that when people estimate how much work they have put in they are usually over estimating it. So when a coworker of your tell you that they have worked 80 hour weeks, take that with a grain of salt. Secondly people might be putting in a lot of time without actually getting a lot of things done. Be the person who works smart instead of hard.

As an example think of the person who works 80 hours a week, week after week, making sure that a system that is unstable stays healthy and when it isn't constantly nurses it back to health. Compare this to the person who instead figures out the few defects in the system that causes it to be unstable and fixes them so the system now runs more or less by itself. Who of these two would you think was most valuable to the team?

Manage distractions

Another aspect of being able to manage your work life balance is to make sure that when you work, you are as productive as possible. In today's world there are so many things that are constantly trying to pull your attention away from what you are supposed to be working on. Especially as you become more senior it will get more important to manage your distractions effectively so that you can actually get things done.

In my own case I have several ways in which people can connect with me and I control obsessively what methods are actually able to notify me immediately instead of me only seeing it when I check them.

  • My pager (Piece of software on my phone). This is the only thing that I allow to wake me up if I sleep.
  • Phone calls and text messages. This is the only other thing on my phone that is allowed to either vibrate or make a sound. The one exception is that I allow my calendar to make a tiny chirp when I have a meeting. Apart from that my phone is silent.
  • Chat applications. I don't let these in any way interrupt me. This includes no visual popups or sounds in any way. They are the first things I check when I take a break from work to see if anybody needs anything from me though.
  • Email. It amazes me that almost everybody I know allows mail to both make a sound and show a popup on their computer. For me email is something I check a few times a day and my personal goal is to read emails within no more than a day after it is sent. If you need something faster from me you would need to ping me in another way or just get lucky.

All this comes down to trying to get as many prolonged periods of time that allow you to actually focus on whatever problem you have at hand without being constantly interrupted. When you inevitably drift off and lose focus, then you go and check if anybody needs something from you. Not the other way around where you lose focus because other people need your input (Unless it is really important and time critical).

Don't hoard knowledge

An extension to managing distractions is to do your best to not hoard knowledge. First of all, if you are the only person who knows something then you are guaranteeing that people will need to bug you to figure out how things are working. Secondly, you are by extension implying that you are sure that your coworkers can in no way improve your work. Now, if that is true then I feel sorry for you because that doesn't sound like a fun place to work.

I have met several people that do this more or less unconsciously probably as a safety mechanism to improve job security. This is misguided though because it ensures that as you progress in your career you are guaranteeing that you will be spending more and more of your time maintaining old projects instead of working on new things and leaving the maintenance to other people and I have hardly ever found an engineer that would not prefer to work on new things rather than maintenance.

Also on this topic is to be open for people to come to you and ask questions and your goal should be to explain it well enough that they understand it well enough to be able to answer the same question if somebody else asks it off them.

As an ending thought I have a request for junior people reading this though to try to not ask the same question too many times before you write it down so that you don't have to ask it again (Again, just trying to manage your senior colleagues distractions).

Wednesday, April 27, 2016

How I studied for the AWS Certified Solutions Architect Professional exam

I recently took (and passed) the AWS Certified Solutions Architect Professional exam and figured I would share how I studied for this test. When I took the associate level of this exam I only had 3 days to study and very little existing experience with AWS before hand and that is definitely not how I would recommend taking these exams. For the professional level exam I had around 3 months of time from the time I started studying to when I had to pass the exam or my associate level exam would have expired.

If you are studying for the associate exam I think the study guide below would probably still work (Although it might be a bit of overkill), just skip the professional level white papers and courses on Linux Academy and Cloud Academy.

Full disclosure, I work for Amazon Web Services as of a couple of months, but the opinions expressed in here are my own.

Prerequisites

Here are the things you should already have done and know before you start thinking about this exam.

  • You will need a broad general knowledge in IT. If you don't have it you can probably pass the associate level exam which is more focused on only AWS specific technology. For the professional level one you will need to have a broad general IT knowledge because they will assume you have a general understanding of how WAN routing, non AWS enterprise software (For instance do you know that Oracle RAC requires multicast and EC2 does not support that).
  • You need to have passed the associate level exam within 2 years.
  • I would highly recommend that you have been using AWS for a while. This will help you wrapping your head around some of the AWS specific concepts that other services are based on easier.

Study Outline

In short here are the things I did to study this.

  1. Start by reading all the recommended white papers listed at the official certification guide site. I would recommend reading both the professional and associate level ones, because everything you knew when you took the associate level exam you will still need for the pro level one.
  2. Sign up for Linux Academy and start taking the classes for first the associate level course and then the professional level course. Don't forget to take the labs as well. Don't take the final quizzes yet (The ones per section are fine though).
  3. Sign up for Cloud Academy and take their classes for associate level and professional level courses. Same thing here, wait with the final quizzes.
  4. Once I finished all the courses I read recommended the white papers again.
  5. Do all the final quizzes from both Cloud and Linux Academy and make sure you get a passing grade. If there are sections that you are weak in then go back and study deeper in those areas, both Linux Academy and Cloud Academy have a lot of content aside from the lectures they recommend for the CSA certification so you don't have to just listen to the same lectures over and over.
  6. Try the sample questions from Amazon, you should be able to answer these by now. If you feel like shelling out some money for trying the sample exam go ahead. I skipped this step myself.
  7. Sign up for the exam.
  8. Read all the recommended white papers again the day before the exam.
  9. Take the exam.

Additional things you might want to consider.

  • Amazon recommends you taking the Advanced Architecting on AWS class. I took this class about 8 months before I took the exam and even though it is a good class I don't think it is that useful for passing the exam.
  • Amazon sometimes have AWS CSA Professional Readiness Workshops and if you have the ability to go to one of these I would highly recommend it. I am not sure if these are held outside of AWS re:Invent conferences though. For the associate level exam I know these workshops are held quite often and they are great too.
  • Qwiklabs is a great resource for practicing your AWS skills. That said if you have your Linux Academy and or Cloud Academy accounts they have labs too that are included in your subscription. These labs are better though if you can afford them.

If you can I would also recommend to start a study group and get together once a week or so and do sample questions and discuss the answers from one of the sources listed above. I did this with some of my work colleagues and I found that very helpful.

Schedule

I would recommend that you plan that studying for this will take at least 2 months. I did it in roughly 3 months, but I only studied actively for about 4 to 6 of those weeks. When I studied I spent roughly two to four hours every evening. Unless you are already a whizz at AWS I doubt you can crank this into a few days, which is very doable for the associate level exam. Roughly I divided my time like this.

10%Initial studying of the white papers.
50%Watching the training videos on Linux Academy and Cloud Academy.
15%Taking labs.
10%Doing quizzes.
10%Additional revisions based on discovered deficiencies from the quizzes.
5%Re-reading the white papers (The second and third time I skimmed through them a lot faster than the initial deep read).

Taking the exam

Don't go until you feel you are ready, so don't schedule the exam until you feel done. At least where I live I could schedule the exam just one day out so you don't need to plan ahead for this.

I am usually a very fast test taker (I took the associate level exam in less than half the time. However time management is going to be important when you take this exam. When I took the test I finished all the questions with around 25 minutes to spare and at that point I had roughly 30% of them marked to be revisited. After going through them all again I had less than two minutes left of my time. It says that the test is 80 questions on the description, but I only had 77 questions in mine. I'm guessing number of questions vary slightly depending on how they are selected randomly.

Cloud Academy vs Linux Academy

Cloud Academy and Linux Academy have a lot of overlap and I recommend that you would subscribe to both of them for this. That said here are the advantages to each of them as far as I experienced it.

  • Linux Academy have more questions in the final quiz and vastly longer study material for the professional exam than Cloud Academy. The entire course in Linux Academy is around 30 hours long and the corresponding course in Cloud Academy is only around 3 hours. And this is not something that can be covered in 3 hours. Their associate level courses are much more on par.
  • Cloud Academy has a much better interface for doing quizzes and revisioning where after each question it tells you the answer and short extract of information about the answer with links to the AWS documentation.
  • Cloud Academy allows you to set the playback speed of the training videos which I like (I feel I can still assimilate information when playing these at around 1.5x speed and it saves time). Linux Academy also had occasional streaming issues in general for me requiring me to sometimes have to restart videos.
  • If you are a student or have an edu address Cloud Academy is a lot cheaper than Linux Academy with $9 per month. If you don't on the other side Linux Academy is cheaper than Cloud Academy with a factor of 2.
  • Both services are very easy to cancel once you are done with your studying in case you don't feel you need them anymore.

When all is said and done though I could probably have passed this with only Linux Academy, but Cloud Academy would not have been sufficient for me (Especially since the training material for the professional level CSA is so short). That said, I still think that the Cloud Academy course provides a valuable alternative to Linux Academy and especially if you can sign up as a student it is so cheap that there is pretty much no reason not to.

Tuesday, July 14, 2015

How to get the most out of your BizSpark azure credits

BizSpark is arguably one of the best deals on the internet for startups. For me the key benefit that it brings is the 5 x $150 per month of free Azure credits. That said they are a little bit tricky to claim.

The first thing you need to do is claim all you BizSpark accounts and then from each of those accounts claim your Azure credits. This blog post describes this process, so start by doing that.

So after doing this you have 5 separate Azure accounts each with $150 per month of usage. However what we want is one Azure account where we can see services from all of these subscriptions at once and that requires a couple of more hoops to jump through. In the end you will end up with one account where you can see and create services from all 5 subscriptions without having to log in and out the Azure management portal to switch between them.

  1. The first step is to pick the one account you want to use to administrate all the other accounts.
  2. This is a bit counter intuitive, but you need to start by adding every other account as co administrators to the account from the first step. Yes, I am saying this correctly. All the other accounts need to be added as administrators to the main admin account (Don't worry, this is temporary).
  3. The following steps need to be done for each of the accounts except for the main account from step 1.
    1. Log into the management console using one of the four auxiliary accounts and go to settings.
    2. Make sure you are on the subscription tab.
    3. Select the subscription that belongs to the account you are currently logged into. It will be the one that has the account administrator set to the account you are currently logged into. If you have done this correct you should see two different subscriptions, one for the subscription you are logged in as and one from the account in step 1.
    4. Click the Edit Directory button at the bottom.
    5. In the image below make sure you select the directory of the main account from step 1. It shouldn't be hard because it will be the only account in the list and pre-selected. If you have already set up any co administrators to the account you will be warned that they will all be removed.
    6. Add the account from step 1 as co administrator to this account as described in the linked to article at the top of the post.
    7. The last step is optional but all the subscriptions will be called Bizspark and hard to keep apart so you might want to rename them.
      1. To do this go to the Azure account portal at https://account.windowsazure.com/Subscriptions. This page tend to be very slow, so be patient following links.
      2. Click on the subscription name. Your screen might look different depending on how many subscriptions you have.
      3. Click on the Edit Subscription Details.
      4. Enter the new name in the dialog presented. You can also optionally change the administrator to the account from step 1 at the top, this will remove the owning account as an administrator from the account all together (Although they are still responsible for billing).
  4. You can now remove all the other accounts from being administrators to the main account that you added in step 2 if you want.

If you follow all these steps when you log into the account from step 1 you should be able to see all of your subscriptions at the same time in the Azure management console like in the screenshot below.

Keep in mind this does not mean that you have $750 to spend as you want. Each subscription still has a separate limit of $150 and you have to puzzle together your services as you create them to keep all of the 5 limits from running out but at least this way you have a much better overview of what services you have provisioned in one place.

Thursday, July 9, 2015

Algorithm for distributed load balancing of batch processing

Just for reference this algorithm doesn't work in practice. The problem is that nodes under heavy load tend to be too slow to answer to hold on to their leases causing partitions to jump between hosts. I have moved on to another algorithm that I might write up at some point if I get time. just a fair warning to anybody who was thinking of implementing this.

I recently played around a little bit with the Azure EventHub managed service which promises high throughput event processing at relatively low cost. At first it seems relatively easy to use in a distributed matter using the class EventProcessorHost and that is what all the online examples provided by Microsoft are using too.

My experience is that the EventProcessorHost is basically useless. Not only does it not contain any provision that I have found to provide a retry policy to make its API calls fault tolerant. It also is designed to only checkpoint its progress at relatively few intervals meaning that you have to design your application to work properly even if events are reprocessed (Which is what will happen after a catastrophic failure). Worse than that though once you fire up more than one processing node it simply falls all over itself constantly causing almost no processing to happen.

So if you want to use the EventHub managed service in any serious way you need to code directly to the EventHubClient interface which means that you have to figure out your own way of distributing its partitions over the available nodes.

This leads me to an interesting problem. How do your evenly balance the load of work evenly over a certain number of nodes (In the nomenclature below the work is split into one or more partitions) which can at any time have a catastrophic failure and stop processing without a central orchestrator.

Furthermore I want the behavior that if the load is completely evenly distributed between the nodes the pieces of the load should be sticky, meaning that the partitions of work currently allocated to a node should stay allocated to that node.

The algorithm I have come up with requires a Redis cache to handle the orchestration and it uses only 2 hash tables and two subscription for handling the orchestration. But any key value store that provides publish and subscribe functionality should do.

The algorithm have 5 time spans that are important.

  • Normal lease time. I'm using 60 seconds for this. It is the normal time a partition will be leased without generally being challenged.
  • Maximum lease time. Must be significantly longer than the normal lease time.
  • Maximum shutdown time. The maximum time a processor has to shut down after it has lost a lease on a partition.
  • Minimum lease grab time. Must be less than the normal lease time.
  • Current leases held delay. Should be relatively short. A second should be plenty (I generally operate in the 100 to 500 millisecond range). This is multiplied by the number of currently processing partitions. It can't be too low though or you will run into scheduler based jitter of partitions jumping between partitions.

Each node also should listen to two Redis subscriptions (Basically notifications to all subscribers). Each will send out a notification that is the partition being affected.

  • Grab lease subscription. Used to signal that the leas of a partition is being challenged.
  • Allocated lease subscription. Used to signal that the lease of a partition has ended when somebody is waiting to start processing it.

There are also two hash keys in use to keep track of things. Each one contains the hash field of the partition and will contain the name of the host currently owning it.

  • Lease allocation. Contains which nodes currently is actually processing which partition.
  • Lease grab. Used to race and indicate which node won a challenge to take over processing of a partition.

This is the general algorithm.

  1. Once every time per normal lease time each node will send out a grab lease subscription notification per each partition that.
    • It does not yet own and which does not currently have any value set for the partition in the lease grab hash key.
    • If it has been more than the maximum lease time since the last time a lease grab was signaled for the partition (This is required for the case when a node dies somewhere after step 3 but before step 6 has completed). If this happens also clear the lease allocation and lease grab hash for the partition before raising the notification since it is an indication that a node has gone offline without cleaning up.
  2. Upon receipt of this notification the timer for this publications is reset (So generally only one publication per partition will be sent during the normal lease time, but it can happen twice if two nodes send them out at the same time. Also when this is received each node will wait based on this formula.
    • If the node currently is already processing the partition it will wait the number of active partitions on the node currently held times the current leases held delay minus half of this delay (So basically (Locally active partitions - 1) * current leases held delay).
    • If the node currently is not busy processing the partition that is being grabbed the node should wait the local active partitions plus one times the current leases held delay (On so fewer words (Locally active partitions + 0.5) * current leases held delay).
  3. Once the delay is done try to set the lease grab hash key for the partition with the conditional transaction parameter of it not being set.
    • Generally the node that has the lowest delay from step 2 should get this which also means that the active partitions on each node should distribute evenly among any active nodes since the more active partitions each individual node has the longer it will wait in step 2 and the less likely it is that they will win the race to own the partition lease.
    • If a node is currently processing a partition but did not win the race in step 2 it should immediately signal its partition to gracefully shut down and once it is shut down it should remove the lease allocation hash field for the partition. Once this is done it should also publish the allocated lease subscription notification. After that is completed this node should skip the rest of the steps.
  4. Check by reading the lease allocation hash value to see if another node than the winner in step 3 is currently busy processing the partition. If this is the case either wait for either the allocated lease subscription notification signaling that the other node has finished from step 3b or if this does not happen wait for a maximum of maximum shutdown time and start the partition anyway.
  5. Mark the lease allocation hash with the new current node that is now processing this partition.
  6. Also after the minimum lease grab time remove the winning indication in the lease grab hash key for the partition so that it can be challenged again from step 1.

When I run this algorithm in my tests it works exactly as I want it. Once a new node comes online within the normal lease time the workload has been distributed evenly among the new and old nodes. Also an important test is that if you only have one partition the partition does not skip among the nodes, but squarely lands on one node and stays there. And finally if I kill a node without giving it any chance to do any cleanup after roughly maximum lease time the load is distributed out to the remaining nodes.

This algorithm does not in any way handle the case when the load on the different partitions is not uniform, in that case you could relatively easily tweak the formula in step 2 above and replace the locally active partitions with whatever measurement of load or performed work you wish. It will be tricky to keep the algorithm sticky though with these changes.

Thursday, June 25, 2015

Designing for failure

One of the first things you hear when you learn about how to design for the cloud is that you should always design for failure. This generally means that any given piece of your cloud infrastructure can stop working at a given time so you need to design for this when constructing your architecture and gain reliability by creating your application with redundancy so that any given part of your applications infrastructure can fail without affecting the actual functionality of the website.

Here is where it gets tricky though. Before I actually started running things in a cloud environment I assumed this meant that every once in a while a certain part of your infrastructure (For instance a VM) would go away and be replaced by another computer within a short time. That is not what designing for failure means. To be sure this happens too, but if that was the only problem you would encounter you could even design your application to deal with failures in a manual way once they happen. In my experience even in a relatively small cloud environment you should expect random intermittent failures to happen at least once every few hours and you really have to design every single piece of your code to handle failures automatically and work around them.

Every non local service you use, even the once that are designed for ultra high reliability like Amazon S3 and Azure Blob Storage can be assumed to fail a couple of times a day if you make a lot of calls to them. Same thing with any database access or any other API.

So what are you supposed to do about it. The key thing is that whenever you try to do anything with a remote service you need to verify that the call succeeded and if it didn't keep retrying. Most failures that I have encountered are transient and tend to pass within a minute or so at the most. The key is to design your application to be loosely coupled and whenever a piece of the infrastructure experiences a hiccup you just keep retrying it for a while and usually the issue will go away.

Microsoft has some code that will help you do this as well which is called The Transient Fault Handling Block. If you are using the Entity Framework everything is done for you and you just have to specify a Retry Execution Strategy by creating a class like this.

    public class YourConfiguration : DbConfiguration 
    { 
      public YourConfiguration() 
      { 
        SetExecutionStrategy("System.Data.SqlClient",
                             () => new SqlAzureExecutionStrategy()); 
      } 
    }

Then all you have to do is add an attribute specifying to use the configuration on your Entity context class like so.

    [DbConfigurationType(typeof(YourDbConfiguration))] 
    public class YourContextContext : DbContext 
    { 
    }

It also comes with more generic code for retrying execution. However I am not really happy with the interface of the retry policy functionality. Specifically, there is no way that I could figure out to create a generic log function that allows me to log the failures where I can see what is actually requiring retries. I also don't want to have a gigantic log file just because for a while every SQL call takes 20 retries each one being logged. I rather get one log message per call that indicates how many retries were required before it succeeded (Or not).

So to that effect I created this little library. It is compatible with the transient block mentioned earlier in that you can reuse retry strategies and transient exception detection from this library. It does improve on logging though as mentioned before. Here is some sample usage.

      RetryExecutor executor = new RetryExecutor();
      executor.ExecuteAction(() =>
        { ... Do something ... });
      var val executor.ExecuteAction(() =>
        { ... Do something ...; return val; });
      await executor.ExecuteAsync(async () =>
        { ... Do something async ... });
      var val = await executor.ExecuteAsync(async () =>
        { ... Do something async ...; return val; });

By default only ApplicationExceptions are passed through without retries. Also the retry strategy will try 10 times waiting for the number of previously tries seconds until the next try (Which means it will signal a failure after around 55 seconds). The logging will just write to the standard output.

Saturday, June 20, 2015

Simple Soap envelope parser and generator

So I figured as a followup to my previous post here is a small sample project of what I would love to find when searching for a person online that is looking for a job.

This library on GitHub is just one class to help you generate and parse a SOAP envelope, something I was surprised to see wasn't actually available in the .Net framework as a stand alone class (Or at least I haven't found it).

Its use is very simple. To create a SOAP envelope you create an instance of the class SoapEnvelope and assign the Headers and `Body` properties (And possible the Exception if you want to signal an error) and then call the ToDocument method to generate the XML document for the SOAP envelope.

To read data simply call the method SoapEnvelop.FromStream or SoapEnvelope.FromRequest and it will return the envelope it parsed from the stream or request. It does support handling GZip content encoding from the request.

Here is a simple round trip example of its use (For more examples check out the tests).

      SoapEnvelope envelope = new SoapEnvelope();
      envelope.Body = new[] { new XElement("BodyElement") };
      envelope.Headers = new[] { new XElement("HeaderElement") };
      XDocument doc = envelope.ToDocument();
      MemoryStream stream = new MemoryStream();
      doc.Save(stream);
      stream.Seek(0, SeekOrigin.Begin);
      SoapEnvelope otherEnvelope = SoapEnvelope.FromStream(stream);

To continue from the previous post from a few days ago. Even though this example is very short it does show a couple of things if I were to evaluate the author of something similar for a job.

  • This is somebody who actually likes to code because otherwise why would he (Or she) even have taken the time to do this.
  • This is somebody that cares about the quality of their code because even though this is a super simple class it contains a small test suite to make sure that it works.
  • This person has at least a decent grasp of the C# and .Net framework and understand how to use inheritance and interfaces to create something new (If you are a coder and doesn't know, it is scary how few people who should know this stuff, do actually know it).

Thursday, June 18, 2015

What I look for when evaluating future hires

Even though I am not a manager and have put a high importance of never becoming one as one of my own personal development goals I do quite often chime in on evaluating future hires both currently for permanent positions or in the past for consultancy contracts and there is one thing that it seems to be an important thing that a lot if not even most software developers are not doing that I put a high premium on when evaluating new candidates for job application.

The first thing I do when I get a resume sent to me for a prospective candidate is that I go to Google and search for their name. If I can't find a single program related name from anything they've ever done online that is a pretty big blotch on their record from my perspective.

My thinking for this is that to be good at software development and like solving problems even if you are straight out of school you will have done one of the following.

  • Asked a question you couldn't figure out, or even better provided an answer to a question for somebody else, on a site like Stack Overflow or CodeProject.
  • Create or participated in an open source project hosted on GitHub or SourceForge.
  • Created some weird obscure website somewhere (Doesn't really matter what it is or how much traffic it has).
  • Create a blog about something. It doesn't have to be old or very active, but at least you've tried.
  • Have some sort of presence I can find on social media, preferably with some comments I can find in relation to software development. Doesn't matter if it is Twitter, Facebook, LinkedIn, Google+ or whatever.

The more of these you can check off the better, but if I can't find you at all that is a huge red flag in my book and you would hopefully be surprised at how common this is for would be software developers.

The problem is if you haven't gotten around to anything of the above to me that signifies that you aren't that into software development and it is just something you do, and generally good coders really like to code and they do it because they like it. If I couldn't make a living for coding I would do it anyway, and most of my public presence online is based on the work I've done when I haven't been collecting a paycheck for it (Since most of the work you do when you do get paid you can't just publish online).

So my advice to anybody who wants to get started working with software development is to sign up for a free account on GitHub and just find a small itch and write an open source application to scratch it. And make sure the repository is associated with your real name so that when I or any other person involved in any hiring search for you we will find it. I can almost guarantee that it will be worth your time.

Thursday, May 7, 2015

C# Task scheduling and concurrency

It is very hard to figure out how the new async Task API for handling threading and concurrency works in .Net 4.5. I have dug around a lot to try and find any documentation on this topic and have mostly failed so when in doubt I decided to simply figure it by writing some test applications that checked how it actually behaved. It is important to note that this is how threading works in a console .Net 4.5 application on Windows 8.1. I would not be surprised if specific numbers of the thread model were different in a server setting, different OS version or even .Net versions. So without further ado here are my findings.

First of all if you simply start a lot of Task's that all run for a long time you quickly notice that by default the .Net runtime will allocate a minimum of 8 threads to run tasks. Then it gets interesting though because for every second that the task queue keep being full another thread is added. This keeps going all the way up to a maximum of 1023 threads. After 1023 threads have been allocated no more threads will be allocated for any reason so any remaining tasks will wait to start until a previous task has completed. If a thread executes no tasks at all for 20 seconds it will be removed from the thread pool.

There are also odd things happening with the order of which tasks are scheduled. For instance if you were to run the following code below it will run very slowly because no threads from the second for loop will be scheduled to run until the thread pool has expanded to run all tasks from the first loop concurrently (So for almost 100 seconds no processing will happen).

      for (int i = 0; i < 100; i++)
      {
        int thread = i;
        firstTasks.Add( Task.Run(() =>
        {
          Thread.Sleep(100);
          // Do something else
          secondTasks[thread].Wait();
        }));
      }

      for (int i = 0; i < 100; i++)
      {
        secondTasks.Add( Task.Run(() =>
        {
          // Do something in the background.
        }));
      }

In fact if you increase the upper bound of i from 100 to 1024 this example will never finish since all the 1023 possible available threads will be taken up with this initial tasks waiting for second tasks to finish which will never be scheduled for execution because of thread exhaustion.

This might seem like a contrived example, but it is actually not that uncommon to end up with a similar scenario if you use non async code inside a task in a complicated multithreaded application. If you instead write the code below like this it will complete almost immediately and not have any issues regardless of how many iterations of the loop you make because the second thread when created within the affinity of the thread that then waits for it actually causes the second thread to be executed immediately on that thread (As long as it hasn't been scheduled to run on another thread already).

      for (int i = 0; i < 100; i++)
      {
        Task.Run(() =>
        {
          Thread.Sleep(100);
          Task secondTask = Task.Run(() =>
          {
            // Do something in the background.
          });
          // Do something else
          secondTask.Wait();
        }));
      }

One last thing you have to be very careful about when it comes to task, especially when using the async syntax is that you have to realize that once you await on something there is absolutely no guarantee that once the execution continues it is on the same thread. So for instance this code is just waiting to creating a deadlock that will be really hard to track down.

      object lockObj = new object();

      Monitor.Enter(lockObj);
      await MethodAsync();
      Monitor.Exit(lockObj);

There really is no way to handle locking securely but if you absolutely need to do locking of a resource while doing async coding you could possibly use semaphores which do not require being reset from the same thread. This generally doesn't lead to good code though and generally if you think about where your synchronization code is you can avoid having locks over awaits but it might take a little bit of extra work.

Sunday, January 25, 2015

Choosing your cloud provider

When you start any coding project you generally need some sort of server capability even if the application your building is not a web site. When choosing your cloud provider there are several different things to think about.

First of all you need to consider if what you need is very basic and will not require a high SLA or the ability to grow with usage you are probably better off choosing a virtual private server provider. If you are fine with a Linux box these can be had extremely cheap. I used to be a customer of Letbox and at the time they provided me with a Virtual Private Server for $5/month, a price that is hard to beat. It is however important to realize that this is not a true VM, it is a specialized version of Linux similar to doing a chroot but also with quotas on memory and CPU usage. This means that these VM:s can only run Linux. That said the price is simply in a league of itself, cheaper usually than even spot instances of AWS EC2.

However once you have something slightly more complicated to run you probably want to go with a "real" cloud provider. These come in two kinds. The first level are companies providing infrastructure as a service (IaaS). This means basically providing virtual machines, storage and networking for them. It is up to you to build everything you need to run off of these primitives. Companies that offer only this kind of computing includes Skytap, Rackspace (Although Rackspace does have some platform services) and many more.

The next level up are the companies that provide platform as a service (PaaS). All of these companies also provide the infrastructure as well if you need it, but on top of this they provide useful packages that they will run for you as managed services to help creating, deploying and running your services easier. These minimally usually include.

  • Load balancing of traffic to multiple servers.
  • Auto scaling of new servers to handle varying load.
  • A fast and scalable NoSQL key value store.
  • A managed transactional database.
  • Web hosting.

There are as I see it three main players in this space and they are Amazon Web Services (AWS), Microsoft Azure and Google App Engine.

Of these Amazon is by far the largest. AWS started out as a mainly platform as a service offering, but now has one of the most complete set of managed services and they have by far the largest set of data centers located all around the world and one region qualified for US government work loads (Having an account on it requires you to be a US citizen so I can not use it). Their infrastructure is truly top notch, but their development tools are not great. Only a few languages have an official SDK (I myself have been missing an SDK for PERL).

Microsoft approached this space from the opposite direction from Amazon and started out by offering specific platform solutions and tightly integrating the development and deployment of Azure applications into their development tool Visual Studio. It is the only cloud provider I am aware of that for a time did not provide IaaS at all (Although they do now). The SDK and tooling for all of their products is truly excellent, especially if you are a .Net C# developer, but many other languages are supported as well. They do unfortunately and understandably run most of their infrastructure on Windows which simply is not as solid as other hyper-visors out there and if you are building a solution that requires reliable quick processing this can be a problem, especially if you have a cluster of synchronized machine this can become really problematic. These synchronization issues usually only occur a few times a month though as the service is migrated to new machines as all the VM:s running the service undergo the monthly Windows patching. However as long as your application does not rely on tight synchronization between several systems you are unlikely to notice it.

Finally there is Google. Their solution is similar to Amazon something that has grown out of their own business and they have several offerings that are obviously simply surfacing of their internal operations like for instance Big Query. Google's infrastructure is fantastic in regards to reliability and performance. They do though in my opinion offer the most narrow platform solution of the big three. What they do provide though is truly top notch, and they are also priced accordingly unfortunately.

Price wise the big three are relatively similarly priced. If your application can take advantage of the AWS spot pricing you can get away with really cheap solutions though. Google is usually the most expensive (I say usually since the prices change all the time for cloud services). One thing that could be worth investigating is if you qualify for a Microsoft Bizspark membership because if you do you will receive $150/month of free credits to use for almost anything in Microsoft Azure (And it also includes licenses to almost every product that Microsoft has in their very extensive portfolio).