<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Simon &#8211; Simon Jakowicz</title>
	<atom:link href="https://www.jakowicz.com/author/simon/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.jakowicz.com</link>
	<description>Just another blogger</description>
	<lastBuildDate>
	Sat, 05 Dec 2026 18:20:01 +0000	</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.1.19</generator>
	<item>
		<title>The Hollow Meridian is on the web and Android</title>
		<link>https://www.jakowicz.com/the-hollow-meridian-is-on-android-bring-a-lantern/</link>
				<comments>https://www.jakowicz.com/the-hollow-meridian-is-on-android-bring-a-lantern/#respond</comments>
				<pubDate>Sat, 05 Dec 2026 18:14:00 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Random Thinking]]></category>

		<guid isPermaLink="false">https://www.jakowicz.com/?p=1810</guid>
				<description><![CDATA[Pack a lantern. Bring a few supplies. If the rain starts doing something suspicious, congratulations. You’ve made it to Bellmouth. The Hollow Meridian is my text adventure about a storm-battered coast, a missing engineer, and a weather engine that might have something to do with both. You can play it right in your web browser... <a class="more-link" href="https://www.jakowicz.com/the-hollow-meridian-is-on-android-bring-a-lantern/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[
<p>Pack a lantern. Bring a few supplies. If the rain starts doing something suspicious, congratulations. You’ve made it to Bellmouth.</p>



<p><strong>The Hollow Meridian</strong> is my text adventure about a storm-battered coast, a missing engineer, and a weather engine that might have something to do with both. You can play it right in your web browser on a computer, tablet, or phone, or get the Android app from Google Play.</p>



<ul><li><a href="https://hollowmeridian.jakowicz.com/"><strong>Play on the web</strong></a></li><li><a href="https://play.google.com/store/apps/details?id=com.jakowicz.hollowmeridian"><strong>Get it on Android</strong></a></li></ul>



<h2>From Colossal Cave to Bellmouth</h2>



<p>The idea started when I visited <a href="https://www.tnmoc.org/our-story">The National Museum of Computing at Bletchley Park</a> and played <em><a href="https://www.acmi.net.au/works/125369--colossal-cave-adventure/">Colossal Cave Adventure</a></em>. A short description and a blinking cursor can make a place feel surprisingly real. The game tells you what’s around you, then leaves you to decide which detail is worth poking at. I wanted to make my own adventure with that feeling, so I traded the cave entrance for a ferry landing and gave the coast some very questionable weather.</p>



<h2>What’s happening in Bellmouth?</h2>



<p>You play a Wayfinder sent to find Orra Vale, an engineer who went up the Rainstairs and never came back. Your first lead is Tamsin, waiting by the ferry. From there, the search takes you through a coast of drowned bells, hidden routes, and machinery that people have very different ideas about how to use.</p>



<p>There are more than 120 locations across 13 regions, so there’s plenty of room to wander. Watch your lantern and supplies, keep track of clues in your journal, and talk to people when their stories don’t quite line up. Some puzzles have more than one solution. The promises you make and the evidence you find can change how the story ends.</p>



<h2>How to play</h2>



<p>Start with <strong>LOOK</strong> to get your bearings, type <strong>EAST</strong> to head towards Bell Market, or try <strong>ASK TAMSIN ABOUT ORRA</strong> to follow your first lead. When the game suggests commands, you can tap them too. The map keeps track of the routes you discover, which comes in handy once you stray from the ferry.</p>



<p><strong>Story mode</strong> gives you more guidance, lighter pressure on supplies, and an undo button. <strong>Wayfinder mode</strong> offers a few nudges while you explore. <strong>Classic mode</strong> leaves you to read the clues and find your own way. If the rain gets the better of you, there’s a <a href="https://hollowmeridian.jakowicz.com/walkthrough">walkthrough with quick help for newcomers</a>.</p>



<h2>Give it ten minutes</h2>



<p>Talk to Tamsin, follow the first detail that makes you curious, and see where you end up. If you find an ending, try going back and taking a different route or keeping a different promise. I’d love to hear what you found. See you at the ferry.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/the-hollow-meridian-is-on-android-bring-a-lantern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>AI Skill for building a new Mac</title>
		<link>https://www.jakowicz.com/ai-skill-for-rebuilding-a-mac-setup/</link>
				<comments>https://www.jakowicz.com/ai-skill-for-rebuilding-a-mac-setup/#respond</comments>
				<pubDate>Mon, 22 Jun 2026 01:28:38 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[AI]]></category>
		<category><![CDATA[LLM]]></category>
		<category><![CDATA[Skills]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1805</guid>
				<description><![CDATA[I’ve been working on a reusable AI skill called mac-setup-bundle-builder. The idea is simple: point an AI coding agent at your current Mac and ask it to create a rebuild bundle for a future machine. Instead of assuming everyone uses the same tools, the skill is discovery-led. It looks for what is actually installed and... <a class="more-link" href="https://www.jakowicz.com/ai-skill-for-rebuilding-a-mac-setup/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[
<p>I’ve been working on a reusable AI skill called <code>mac-setup-bundle-builder</code>.</p>



<p>The idea is simple: point an AI coding agent at your current Mac and ask it to create a rebuild bundle for a future machine. Instead of assuming everyone uses the same tools, the skill is discovery-led. It looks for what is actually installed and configured: apps, package managers, shells, dotfiles, language runtimes, version managers, editor extensions, containers, VMs, local services, AI tools, repos, app settings, and system settings.</p>



<p>The generated bundle is designed to be copied to a new Mac and used by an AI setup agent there. It can include:</p>



<ul><li>a setup prompt</li><li>a structured manifest</li><li>setup order instructions</li><li>package and app inventories</li><li>dotfiles and editor extension lists</li><li>restore/setup scripts</li><li>live progress logging</li><li>verification checks</li><li>a final HTML report</li></ul>



<p>The skill is careful about private data. It should not commit secrets, tokens, browser sessions, SSH keys, app databases, or account caches. Those are documented as manual or private-transfer items instead.</p>



<p>You can find it here:</p>



<p><a href="https://github.com/jakowicz/skills">github.com/jakowicz/skills</a></p>



<p>Install with:</p>



<pre class="wp-block-code"><code>npx skills add jakowicz/skills</code></pre>



<p>The first skill in the repo is:</p>



<pre class="wp-block-code"><code>mac-setup-bundle-builder</code></pre>



<p>I built it after creating my own Mac setup bundle, then generalised the workflow so it can adapt to other people’s machines rather than just mine. It is still early, but the goal is to make rebuilding a development machine less of a manual checklist and more of a reproducible and inspectable process.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/ai-skill-for-rebuilding-a-mac-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>SOLID Principles &#8211; Revisited</title>
		<link>https://www.jakowicz.com/solid-principles-revisited/</link>
				<pubDate>Mon, 08 Feb 2016 09:46:41 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://staging.jakowicz.com/?p=1644</guid>
				<description><![CDATA[I recently rewrote an article on APIE, an article I originally wrote over 2 years ago. Now I am going to rewrite another article I wrote 2 years ago on the SOLID principles. My views on the SOLID principles, have stayed largely the same, however my knowledge of these principles has matured. This hopefully means,... <a class="more-link" href="https://www.jakowicz.com/solid-principles-revisited/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<h2>I recently rewrote an article on <a href="/apie-revisited/">APIE</a>, an article I originally wrote over 2 years ago. Now I am going to rewrite another article I wrote 2 years ago on the SOLID principles.</h2>
<p>My views on the SOLID principles, have stayed largely the same, however my knowledge of these principles has matured. This hopefully means, I&#8217;ll be able to explain each principle in greater detail and be a lot more concise on each subject. I also like to think my writing style has matured and so I&#8217;m able to express myself better with less waffling, which is always a plus.</p>
<p><span id="more-1644"></span></p>
<h2>A brief introduction</h2>
<p>The SOLID principles are 5 basic OOP principles that together aid developers to build systems, which are easy to maintain and extend over a large period of time. In my recent <a href="/apie-revisited/">rewrite on APIE</a>, I talked a lot about abstraction, as I believe it&#8217;s the most important of the 4 APIE concepts. That leads me onto, well what are the SOLID principles? <span class="snippet">The SOLID principles stand for Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion</span>.</p>
<p>Last time I wrote about the SOLID principles, I wrote how the open-closed principle and interface segregation principle were less important than the others. This time I&#8217;m not saying anything of the sort. Each principle is equally as important, however I will say the open-closed principle is very easy to violate. If you could write applications without violating this principle, you would potentially have an extremely robust piece of software. I&#8217;ll cover why in the open-closed section.</p>
<p>As I step through each principle, you&#8217;ll begin to see how intertwined each of them are. When you start violating one of them, you&#8217;re almost certain violating two or three of them. In my opinion the most important thing to understand about the SOLID principles, is that everything revolves around programming to an interface. It&#8217;s an age-old rule within OOP, but it&#8217;s just as important now as it has ever been. Be warned, it may sound like I&#8217;m repeating myself at times and that&#8217;s because I will be. The SOLID principles are tangled together like a bowl of good chow mein, so unfortunately there will be some cross referencing, however I&#8217;ll do my best to limit this.</p>
<h2>Single Responsibility</h2>
<p><i>&#8220;A class should have only one reason to change&#8221;</i></p>
<p>This principle is by far the most commonly known principle of the five. Even if you&#8217;ve never heard of it before, you&#8217;ll probably be complying to single responsibility at least a little. The principle states that when building your classes, <span class="snippet">&#8220;make sure that each class does one thing and one thing only&#8221;</span>. This can also be described as having only one reason to change. If you&#8217;re class requires updating, to support any more than one piece of functionality, it would be breaking single responsibility. You can think of it a little like the Unix philosophy, just with classes instead of programs.</p>
<p>The all consuming point that I want to talk about here, is the concept of knowers and doers in your application. Every class you create should either be a knower or a doer but never both, doing so would violate single responsibility. Lets discuss what being a knower entails.</p>
<h3>Knower Classes</h3>
<p><span class="snippet">A knower is simply a class which stores data, but does not have methods to operate on its data</span>, it simply stores data for other objects to consume and use. These objects are commonly referred to as Data Transfer Objects (DTO). The most common example of a DTO would be your models, but they could also be value-objects. Models are generally populated from your database data, using some form of Data Access Object (DAO). This could be done using an Object Relational Mapper (ORM), repository pattern or something else, whatever tickles your fancy.</p>
<p>Models that have no doer methods, i.e. they contain no behaviours, are called anaemic models and they&#8217;re extremely common in OOP. Despite their popularity, there are another group of people who will tell you <span class="snippet">anaemic models are an anti-pattern, the spawn of the devil even.</span> &#8211; <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html">Martin Fowler wrote a must read article on just this</a>. The general reason why anaemic models are disapproved of, is because they remove the benefits that come with bundling data and behaviours &#8211; encapsulation. It&#8217;s a fair point, after all it&#8217;s the very core benefit of OOP over procedural code. So the argument is, should we allow some logic in our models, whether that be validation rules, business rules or something else? I don&#8217;t believe there is a right or wrong answer to this question. The advantage of keeping your models anaemic, is that you don&#8217;t run the risk of always thinking, just one more method and ending up with a monolith, 6 months down the line. However if you and your team are confident in keeping your models under control, whilst adding some logic to them, I think that&#8217;s the perfect medium. There&#8217;s nothing wrong with abstracting out methods later down the line and it&#8217;s nothing to be ashamed of either. Once you feel the logic is getting to complicated for your models, it&#8217;s better to abstract some of that out, rather than letting the code rot even more. As I mentioned above, I highly recommend Martin Fowlers article on this. I don&#8217;t want to go into massive detail, as it&#8217;s not essential to single responsibility.</p>
<p>A brief word on frameworks. Frameworks are a great, they help us build applications quick. But they all have one thing in common. They all go completely apeshit when it comes to helper methods. As I mentioned above, anaemic models are fine imo, models with some simple behaviours are also fine. Abstract models that are 5,000 lines long, follow active record and have endless methods working on the global scope, are not fine. Yet every framework I&#8217;ve ever worked with including Symfony (PHP), Laravel (PHP), Yii (PHP, Phalcon (PHP), Django (Python) and Rails (Ruby), all do it. The important thing to take away is, just because they all do it, doesn&#8217;t make it right. They all have hundreds if not thousands of contributors to their frameworks and are somehow able to maintain their code. You and your tiny team, won&#8217;t be able to and you wouldn&#8217;t want to either.</p>
<h3>Doer Classes</h3>
<p>Single responsibility really lives within the realm of the doers. Knower&#8217;s know stuff but that&#8217;s it, they&#8217;re pretty simple. Doers should do only one thing. Although they could do two, three, five, ten, one hundred or any other amount of things. So let&#8217;s discuss why they should only do one thing.</p>
<p>Lets go back to the framework abstract model example. You might think that a single class that can perform every possible action on a user is following single responsibility, but you would be wrong. Abstract models in frameworks usually perform many, many tasks e.g., Pulling data from the database, storing data, saving records to the database, saving relationships, validating forms, performing diffs on objects, hydration, outputting result, caching, exporting and so much more. Each of these responsibilities should be performed by a completely separate set of classes to comply with single responsibility.</p>
<p>Great, so splitting up all these actions into separate classes, will help us comply with single responsibility, but what makes that any better? Great question Sherlock. The key thing to remember when writing software, is that you&#8217;re not just writing code for machines, more importantly you&#8217;re writing code for humans. One of my favourite quotes goes like this, &#8220;<span class="snippet">Always code as if the guy who ends up maintaining your code, will be a violent psychopath who knows where you live.</span>&#8220;. We&#8217;ve all opened a class to find it has over 5,000 lines of code, hell I&#8217;ve stumbled across PHP classes with over 30,000 lines of code. It&#8217;s overwhelming, impossible to find what you want, messy, unmaintainable and damn right scary. Any developer who is worth their salt and roped into working in an environment like that, will soon be freshening up the old curriculum vitae and find a role worthy of them. The point here is, by writing classes that have a single responsibility, you&#8217;re also writing code which can more easily be maintained, not just for a few weeks, but months and years.</p>
<p>On top of having human friendly code, which is obviously a huge win. When complying to single responsibility, you&#8217;ll find it way easier to substitute responsibilities between different abstractions. For example, going back to the framework abstract model example, your application might be storing all its data in MySQL, but you want to start storing certain models in MongoDB. To do so you&#8217;re going to have to throw a bunch of horrible conditions into your models like this:</p>
<pre class="prettyprint linenums">
if useMysql
    // Save to Mysql
elsif useMongo
    // Save to MongoDB
else
    // Throw exception
</pre>
<p>This obviously isn&#8217;t maintainable or easily extensible. In fact as soon as you start putting if statements inside your classes to control logic paths, it&#8217;s a pretty safe bet that you&#8217;re violating the single responsibility principle. Wouldn&#8217;t it be much cleaner, if instead you had a data mapper class for MySQL and another for MongoDB, which saves models to the respective database. You could then use the strategy pattern to inject the data mapper that you want to use in the client class. This allows you to separate your saving logic for each database system, keeping your classes laser focused and easy to maintain. If you wanted to start saving records to Neo4J as well, you could just add a new data mapper class and you&#8217;re done.</p>
<p>On top of all of those benefits, you&#8217;ll also find testing your classes way easier. The more you can substitute dependencies out into abstractions the more you can mock the dependencies during testing, keeping your tests laser focused too.</p>
<h2>Open-Closed</h2>
<p><i>&#8220;Software entities … should be open for extension, but closed for modification&#8221;</i></p>
<p>The general idea behind the open-closed principle, is that once a entity (class or method) has been written, it should be closed for modification i.e., it should never be edited again. The benefit to doing this is, if you never have to update your existing classes, then you never have to worry about breaking existing functionality when creating new functionality. So how do we achieve this, well programming to an interface is a great first step. By programming to an interface, we are able to build new abstractions by extending existing interfaces. What this means is, we can change the behaviour of a class without modifying the source code of our existing classes.</p>
<p>A tell-tale sign that you may be violating the open-closed principle is if inside of your methods you have to check the instance of an argument. Then based on the type of argument that is passed in different behaviours should take place. The best way to make sure you never get into this scenario, is to always create interfaces for your abstractions and always type hint your method arguments where possible to comply to an interface. If you do this throughout your application, you&#8217;ll never need to modify your existing entities to create new functionality. There is a catch though, what if we need to add a new method to our interfaces?</p>
<p>Technically this also violates the open-closed principle, however like I said, sometimes you just have to violate this principle, there really is no way around it. The less you modify your existing entities the better, but sometimes it absolutely necessary. I don&#8217;t think anyone would agree that over-engineering is a good thing, so we&#8217;re hardly going to create a class that has every method we&#8217;ll ever need, straight off the bat. The upshot being, we all agree that it&#8217;s basically impossible to comply to the open-closed principle, so why not just make refactoring part of the principle. Maybe one day this will be the case, but for now comply to open-closed as best as you can, always type hint using your interfaces, but don&#8217;t be afraid to refactor and add new methods where you see appropriate.</p>
<h2>Liskov Substitution</h2>
<p><i>&#8220;Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program&#8221;</i></p>
<p>Liskov substitution and open closed almost go hand in hand with one another. The main thing we took away from the open-closed principle, was that by programming to an interface, we can stop ourselves from modifying existing source files. Instead we can change the behaviour of a class by simply substituting in a new implementation.</p>
<p>Liskov substitution is very similar, but where open-closed focuses on your method arguments, liskov substitution focuses on the return types of your methods. What the Liskov substitution principle defines, is a set of rules that each implementation of an interface or child class should adhere to, in order to be truly substitutable. This can quite simply be described as being polymorphic.</p>
<p>A tell-tale sign that you&#8217;re probably violating the liskov principle is that you&#8217;re type checking a response inside a client class. In some languages you&#8217;re able to define the return type of your methods and these can be defined in your interfaces or parent classes, as a contract for your concrete classes to follow, but not all languages support this functionality. So for example you may have two classes which return user records, one set comes from Redis as a standard array or list. Another set may come from MySQL as a collection object. This means that inside your client code you need to type check the response before your can operate on the data. This may seem like not too big a deal with only two types of response, but when you add another source, say Neo4J, with another return type, you&#8217;ll start to see the messiness creep in.</p>
<p>When your child classes return different types of response, they don&#8217;t adhere to the contract set by their parent. This is what causes us to have to type check the responses, if all of our concrete classes had adhered to a contract and all returned the same object type, the response could be handled in exactly the same manner, regardless of the implementation. Not only that, this also would also violate the open-closed principle, because we would be forced to update the client class to support the new return type, which means we would be breaking the closed for modification rule.</p>
<p>As I mentioned above, unfortunately not all languages support return type declarations, in these cases we have to use docblocks to define return types. Obviously this doesn&#8217;t have the same effect as return type declaration, but some languages have static code analysis tools that will read your docblocks and try to find violations for you.</p>
<p>On top of return type declarations, liskov substitution defines some additional rules for staying polymorphic.</p>
<h3>Method Signatures</h3>
<p>I don&#8217;t know about all OO languages, but in the ones that I&#8217;m familiar with, it&#8217;s possible to override method declarations, with completely different arguments. All methods in a child class should match the signature of the same method in their parent class or become more loose. Becoming more loose is always a confusing concept, it always seems more natural for a child class to become tighter. However making the contract for a child class tighter than the parent, would mean certain valid arguments that could be passed to the parent, would not be valid for the child, meaning the child does not adhere to the parents contract.</p>
<p>Lets explain that with a simple example. You have 6 classes named Person, Woman, Man, Car, Ferrari, Mini. Man and Woman are both child classes of Person, Ferrari and Mini are both child classes of Car and Car is a dependency of Person. Lets put that into code with some PHP.</p>
<pre class="prettyprint linenums">
class Car {}

class Ferrari extends Car {}

class Mini extends Car {}

class Person {
    public function __construct(Car $car) {
        $this->car = $car;
    }
}

Class Man extends Person {
    public function __construct(Ferrari $car) {
        $this->car = $car;
    }
}

class Woman extends Person {}
</pre>
<p>Despite the code above actually lacking any real use, you can see that the Man class has broken the contract defined by its parent class &#8211; Person. The Person class states in its contract that it accepts any instance of Car, that could be the actual Car class or Ferrari or Mini. The Woman class doesn&#8217;t override the contract in any way, so it&#8217;s fine, however the Man class states only Ferrari is a valid dependency. It has updated the contract, making it tighter and no longer comply to its parents contract. Liskov substitution has been violated.</p>
<h3>Exceptions</h3>
<p>When throwing exceptions inside a child class, the exception thrown should always be more specific than any exception thrown inside the parent class. That&#8217;s the other way round to method signatures, but it makes sense here. Lets create 2 new exception classes, CarException which extends Exception and FerrariException which extends Car Exception.</p>
<pre class="prettyprint linenums">
class CarException extends Exception {}

class FerrariException extends CarException {}
</pre>
<p>Lets assume that inside the Car class we created a drive() method that threw a CarException when the gearstick is in neutral. Inside the Ferrari class we threw a FerrariException if the gearstick is in neutral. This would be perfectly valid and would not violate the liskov substitution principle. When Calling the the Car classes drive() method, the client knows it might have to handle a CarException, which will automatically catch all child exceptions like FerrariException. However if the Ferrari classes drive() method was to throw a basic Exception, this would violate the liskov substitution principle, because the Car classes contract towards exceptions has changed.</p>
<p>P.s. No sexist notions towards men drive Ferraris and woman drive minis was intended.</p>
<h2>Interface Segregation</h2>
<p><i>&#8220;Many client-specific interfaces are better than one general-purpose interface&#8221;</i></p>
<p>Interface segregation is an extremely simple principle and compliments the single responsibility principle perfectly. Where single responsibility focuses on building small but highly cohesive software components, interface segregation focuses on building interfaces which are small, focused and highly cohesive. It simply states that no clients should ever be forced to implement an interface that it does not need. More specifically this means that no class should ever be required to implement a method it doesn&#8217;t need, just because of an interface the class implements. The solution is pretty simple, just make your interfaces smaller and have your class implement as many interface as it needs. There is no harm in having a class which implements multiple interfaces, interface which contain a singe method are absolutely essential in many situations.</p>
<p>As an example imagine you had 2 classes Eagle and Ostrich, they both implement an interface called bird which enforces the definition of certain methods like eat, sleep and fly. That all sounds great, until you realise that an Ostrich may be a bird, but it can&#8217;t fly. So what do you put in the Ostrich classes fly method? You&#8217;re forced to return a null or falsey value, as it&#8217;s an invalid method call. This obviously isn&#8217;t great and violates the interface segregation principle.</p>
<p>The correct solution would be to define two interfaces, Bird which contains the eat and sleep methods and FlyableInterface which contains the fly method. This way you can have both the Eagle and Ostrich classes implement the Bird interface, but also have the Eagle class implement the FlyableInterface. Doing this will ensure that your Ostrich class is not being forced to implement an interface it does not need and now complies to the interface segregation principle.</p>
<p>Here&#8217;s an example of this in PHP</p>
<pre class="prettyprint linenums">
interface Bird {
    public function eat();
    public function sleep();
}
interface FlyableInterface {
    public function fly();
}
class Eagle implements Bird, FlyableInterface {
    public function eat() { return 'Eagle Eating'; }
    public function sleep()  { return 'Eagle Sleeping'; }
    public function fly()  { return 'Eagle Flying'; }
}
class Ostrich implements Bird {
    public function eat() { return 'Ostrich Eating'; }
    public function sleep()  { return 'Ostrich Sleeping'; }
}
</pre>
<p>Interfaces which contain methods which not every implementation will need, are called fat interfaces and these not only violate interface segregation, they also violate single responsibility. By defining tiny reusable interfaces, we are able to type cast arguments to a very specific set of behaviours.</p>
<p>Lets say for example we have a Mailer class which sends emails, but requires an object which contains a method called getEmail, this could be a User class for example. We could type hint the Mailer class to only accept instances of the User class, which would ensure a getEmail method will always exist, great. But what if we want to start sending emails to email addresses stored in other classes, for example a NightlyMonitor class. We may create a class called NighlyMonitor, which also contains a getEmail method. This new NightlyMonitor class fits the requirements to be used in the Mailer class, apart from it&#8217;s not a User class, so how do we allow the Mailer class to accept instances of both User and NighlyMonitor? The answer is with a tiny interface, lets call it MailableInterface which defines the requirement of a single method &#8211; getEmail. After that, make sure the User and NightlyMonitor class implement that interface. Now in the Mailer class, we can make sure an instance of MailableInterface is provided instead of an instance of User. Now any class you create that has an email address you want to send emails to, you can have the class implement MailableInterface and it&#8217;s ready for action.</p>
<p>Hopefully that isn&#8217;t too fuzzy, here&#8217;s that exact example in PHP.</p>
<pre class="prettyprint linenums">
interface MailableInterface {
    public function getEmail();
}
interface MailerInterface {
    public function send();
}
class User implements MailableInterface {
    public function getEmail() { return 'top@secret.com'; }
}
class NighlyMonitor implements MailableInterface {
    public function getEmail() { return 'eventopper@secret.com'; }
}
class Mailer implements MailerInterface {
    public function send(MailableInterface $mailable) {
         $email = $mailable->getEmail();
    }
}
</pre>
<p>It&#8217;s a pretty basic example, but as you can see, the Mailer class now accepts both instances of the User and NightlyMonitor classes. Your Mailer class is now a lot more reusable and no longer depends upon a concrete User. All it cares about is that a getEmail method exists, so it has somewhere to send its mail too.</p>
<h2>Dependency Inversion</h2>
<p><i>&#8220;Depend upon Abstractions. Do not depend upon concretions. Dependency injection is one method of following this principle.&#8221;</i></p>
<p>Last but certainly not least, dependency inversion. A common belief is that dependency inversion and dependency injection mean the same thing, but that&#8217;s not true. A more accurate description would be that dependency inversion can be achieved using dependency injection. That&#8217;s not so say that dependency inversion cannot be achieved using other approaches though.</p>
<p>The golden rule to achieving dependency inversion goes a little like this.</p>
<p><em>High level modules should never depend upon low level modules, instead they should depend upon abstractions. Low level modules should also depend upon these same abstractions.</em></p>
<p>So what are high and low level abstractions? You can think of high level abstractions as your classes which say I want to perform task xyz, but have no idea what&#8217;s involved in achieving that, therefore they delegate the responsibility to a low level abstraction. Low level abstraction are the clever clogs classes of your application, they&#8217;re the classes that know exactly how to do what the high level classes ask of them.</p>
<p>You can think of a high level classes like your car, it can perform behaviours like drive. Then you can think of your low level classes like your cars engine, this can perform tasks like, air and petrol intake, spark plug ignition and fume releasing. Your car has no idea how to perform these tasks, so it simply delegates the responsibility to the engine aka the clever clogs, which knows exactly what to do.</p>
<p>So how does the high level class (Car) consume the low level class (Engine), the answer is dependency injection. When instantiating the Car class the Engine class can simply be provided as a dependency. That&#8217;s pretty simple and was explained in the open-closed principle. But what is meant by high and low level modules should depend on the same abstraction.</p>
<p>Just like all of the SOLID principles, what this is referring to, is programming to an interface. By making sure that the Engine class implements an EngineInterface and that the Car class can be passed any instance of EngineInterface not just Engine, our high and low level modules now depend upon the same abstraction.</p>
<p>That really is the crux of dependency inversion, although it has separate goals to the open-closed principle, they&#8217;re both achieved using exactly the same approach. Just like with the open-closed principle you reap all the same rewards, like decoupling your modules, making changes easier and less spaghetti like, also easily being able to test your code.</p>
<h2>Conclusion</h2>
<p>That&#8217;s one of my most meaty blog posts to date, sorry about that. You probably got bored of me repeating myself so often, but it&#8217;s not without good reason. All of the SOLID principles are very tightly coupled and they really do all boil down to one thing &#8211; program to an interface.</p>
<p>I&#8217;d go as far as saying that&#8217;s the most important aspect of OOP, when trying to keep a healthy, maintainable, easy to extend and human friendly application.</p>
<p>Thanks for reading.</p>
]]></content:encoded>
										</item>
		<item>
		<title>What is APIE &#8211; Revisited</title>
		<link>https://www.jakowicz.com/apie-revisited/</link>
				<comments>https://www.jakowicz.com/apie-revisited/#respond</comments>
				<pubDate>Fri, 05 Feb 2016 09:40:50 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[OOP]]></category>
		<category><![CDATA[Abstraction]]></category>
		<category><![CDATA[APIE]]></category>
		<category><![CDATA[Encapsulation]]></category>
		<category><![CDATA[Inheritance]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Polymorphism]]></category>

		<guid isPermaLink="false">http://staging.jakowicz.com/?p=1641</guid>
				<description><![CDATA[You&#8217;ve probably heard of APIE. If you haven&#8217;t, the most basic explanation is, &#8220;APIE is an acronym for the 4 paramount concepts within OOP, namely abstraction, polymorphism, inheritance and encapsulation.&#8221; Each of these concepts is a huge discussion point in its own right, then there&#8217;s how they all fit together to form OOP. Many people... <a class="more-link" href="https://www.jakowicz.com/apie-revisited/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<h2>You&#8217;ve probably heard of APIE. If you haven&#8217;t, the most basic explanation is, <em>&#8220;APIE is an acronym for the 4 paramount concepts within OOP, namely abstraction, polymorphism, inheritance and encapsulation.&#8221;</em></h2>
<p>Each of these concepts is a huge discussion point in its own right, then there&#8217;s how they all fit together to form OOP. Many people have written multi-hundred page documents and book explaining these principles in depth and how to make use of them within different programming languages. Needless to say, I&#8217;m not going into that detail and I&#8217;m solely going to be discussing the language agnostics. By the end of this article, I hope to have explained each of the four concepts, covering a mix of what they are; how you should make use of them and how they all work together to keep you your code clean and human friendly.</p>
<p><span id="more-1641"></span></p>
<h2>Abstraction</h2>
<p>When I ask people what abstraction means to them, the most common answer I get is something along the lines of &#8220;Abstraction helps to write reusable code&#8221;. That&#8217;s not an incorrect answer, by abstracting out common functionality, we are indeed making a reusable, isolated, unit of code, that we like to call a class. This concept is called data abstraction and it&#8217;s generally achieved by complying to the DRY (Dont Repeat Yourself) and OAOO (Once And Only Once) principles.</p>
<p>The second form of abstraction is called abstraction of control. The goal here being to remove complexity from your client, by hiding the complexity behind a common interface. One option is to hide the complexity inside private methods or helper methods, although we can do better than that. When you start writing helper methods, a lot of the time, you&#8217;ll be violating the single responsibility principle. You may choose to ignore this, because you can now write one line of code instead of three which sounds great. The probleb with helper methods is that before you know it, you have bloated classes with helper methods coming out of your ears and the initial purpose of your class has been lost in a mess of global, static mess.</p>
<p>So what are the alternatives to achieving abstraction? There are quite a few, but the main one I want to talk about is something we call Polymorphism. So lets talk about that.</p>
<h2>Polymorphism</h2>
<p>Before I can answer how Polymorphism helps us achieve abstraction, I should probably talk a little about polymorphism. Polymorphism in greek means many forms and that&#8217;s exactly what it means in programming too. Bjarne Stroustrup aka the creator of C++ (Pretty big fish) labelled polymorphism like this <em>&#8220;polymorphism is the provision of a single interface to entities of different types&#8221;</em>. What this means in layman&#8217;s terms is, entities which can be used interchangeably, should all follow a common interface.</p>
<p>The benefit here is, as soon as you start abstracting out complexity into separate units, you can begin to inject these abstractions, as dependencies into your client class. This type of polymorphism is called delegate polymorphism and it&#8217;s what I&#8217;m want to talk about.</p>
<p>So, creating multiple classes which can be injected into a client class interchangeably is delegate polymorphism. It makes perfect sense too, what you are doing is delegating the responsibility of a task to one of many possible abstractions, which all follow a common interface. How you go about making sure your client code receives an instance of the interface you are looking for, depends on the language you are using. In strict type languages, you&#8217;ll be able to use type checks using interface and abstract classes, in other languages you can rely on duck typing.</p>
<h2>Inheritance</h2>
<p>Inheritance as one might imagine, is the art of creating children (child classes), which inherit their genes (functionality) from their parents (parent or abstract classes). In many languages you can only inherit from one parent, which ruins that analogy completely, but let&#8217;s not worry about that for now. So by that analogy, inheritance should be a way of achieving polymorphism, and it is. By defining a parent class, you will be able to use polymorphism to delegate functionality. This has the benefit of being able to easily test a single unit of code, without worry about its dependencies. That&#8217;s another huge talking point, which I won&#8217;t get into here.</p>
<p>So Polymorphism helps us achieve abstraction and inheritance helps us achieve polymorphism. What else is inheritance good for? Just like abstraction, the most common answer is to write reusable code. But this time you would be wrong &#8211; sort of, we&#8217;ve already covered that abstraction helps us to write reusable units of code and how dependency injection helps us to pass these dependencies around. This is where it get fuzzy, inheritance can help with reusability too, but only if you&#8217;re smart about it. Inheritance is an incredibly easy way of defining common functionality, because you can bundle all kind of logic into your parent classes, but again this isn&#8217;t human friendly and so abstraction is usually preferred. It&#8217;s hard to say exactly when you should use inheritance as it takes common sense on a case by case basis. One of the golden rules to programming is composition over inheritance, so be careful not to flood your parent classes with helper methods and always remember, Don&#8217;t Repeat Yourself. If you follow these simple rules you should be fine. As a rule of thumb, if you parent classes start exceeding 300 lines of code you want to start thinking about shipping some of that off to an abstraction layer.</p>
<h2>Encapsulation</h2>
<p>Contrary to common belief, encapsulation isn&#8217;t all about data hiding, for sure you can encapsulate data within your classes and keep that data private, in fact you should. However encapsulation is more to do with bundling data and methods which can operate on the data, to form a unit.</p>
<p>A lot of programming languages have the notion of visibility. PHP, Java and C++ all have public, protected and private methods; Ruby also offer these 3 visibilities although they work a little different; Python and JavaScript only supports public methods, although you can create private methods using a few tricks. Whatever the language you&#8217;re using supports, you should always make sure your data has the tightest possible visibility, until the time you need to loosen them. This will allow your objects to control their own data, rather than passing responsibility off to the client.</p>
<p>The final point worth mentioning is regarding your constructor methods. It&#8217;s all too easy to bundle a huge collection of parameters into your constructors. You start with 2 or 3, which is fine, then the need arises for another, then another and it goes on. Before you know it, you have 10 parameters and you may as well start over, before your name is tarnished for good. The point here is that your constructors should only ever accept parameters which they require to operate as a complete object. If you have a class which has 10 valid dependencies, it may well need a refactor altogether, but if you don&#8217;t have time for that, you may want to consider making use of a creational pattern, <a href="/builder-pattern-in-php/">builder</a> would work well here.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/apie-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 10 – Internals and Final Thoughts</title>
		<link>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/</link>
				<comments>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/#respond</comments>
				<pubDate>Mon, 28 Dec 2015 21:26:04 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1348</guid>
				<description><![CDATA[This is post 10 of 10 in the series &#8220;MongoDB&#8221; It&#8217;s taken me a year to write this MongoDB series, admittedly I have had a lot of down time, but this is the finale. One thing I&#8217;ve not given much explanation too, is the internals of MongoDB and how it works under, that what we&#8217;ll... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 10 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>It&#8217;s taken me a year to write this MongoDB series, admittedly I have had a lot of down time, but this is the finale. One thing I&#8217;ve not given much explanation too, is the internals of MongoDB and how it works under, that what we&#8217;ll be covering here.</h2>
<p>The main internals I want to cover are, how Mongo actually manages it write concerns using locks and how journaling works. After that, I&#8217;ll probably ramble on for a bit and have a big emotional climax.</p>
<p><span id="more-1348"></span></p>
<h2>Locks</h2>
<p>MongoDB has a pretty expansive set of locks. When I fist started this series, the latest version of MongoDB was 2.6, if I remember correctly, now version 3.2 is the latest. The internals between version 2 and 3 changed a hell of a lot and these changes have propagated down to the locks.</p>
<p>One of the major changes between version 2 and 3 was the switch between the default storage engine. Previously MMAPv1 was the default, now <a href="https://docs.mongodb.org/manual/core/wiredtiger/#storage-wiredtiger">WiredTiger</a> is the default. The changes between these storage engines is sufficient enough to warrant its own blog post, but I&#8217;m going to focus the best new feature of the bunch; document level concurrency.</p>
<p>Document level concurrency, allows MongoDB to put a lock on any document in any collection. Previously to version 3 of MongoDB, this wasn&#8217;t possible and a lock would have to be put on the entire collection for every write. Obviously this is a humongous improvement.</p>
<p>You can get a list of all locks which are current set on your database by running:</p>
<pre class="prettyprint linenums">
db.currentOp()
</pre>
<p>You can get a list of all existing locks by running:</p>
<pre class="prettyprint linenums">
mongotop --locks
</pre>
<p>Apart from the document locks which are created when performing CRUD operation, there are a bunch of operations and commands that will lock up an entire database, lets cover some of these:</p>
<ol>
<li>Compact &#8211; Used to reclaim disk space.</li>
<li>Repair &#8211; Used when journaling is disabled and there is a bad shutdown causing data to corrupt.</li>
<li>MapReduce &#8211; Used to perform complicated queries across a cluster.</li>
<li>Copying a database</li>
<li>Journaling to disk from memory creates a system wide lock for a short interval.</li>
</ol>
<p>For more information on lock, check out the <a href="https://docs.mongodb.org/manual/faq/concurrency/">MongoDB concurrency docs</a></p>
<h2>Journaling</h2>
<ol>
<li>Every write to a mongod is first to send to an in memory journal</li>
<li>After 100ms (configurable), journal entries are then written to a disk journal on disk in$DB_PATH/journal/*, so in the event of a crash, no more than 100ms of data will be lost.</li>
<li>Data is read from the Journal on disk and written to the database every 60 seconds or after 2GB of journal entries are written, whichever comes first.</li>
<li>Journal files are removed after a clean shutdown.</li>
<li>On a crash of MongoDB, mongod will replay the journal on reboot.</li>
<li>Journaling can be disabled, however if you have a hard crash you may get corrupt data on when using the MMAPv1 storage engine. The WiredTiger storage engine is slightly more intelligent and uses a checkpoint system, so in the event of a hard crash, you will not get corrupt data but you will lose some data. For these reasons it is never advised to have journaling disabled and for that reason, I&#8217;m not even going to tell you how to disable it.</li>
</ol>
<p>The write to the disk journal every 10ms instead of every 100ms, you would run</p>
<pre class="prettyprint linenums">
db.adminCommand({ "setParameter": 1, "journalCommitInterval": 10 })
</pre>
<h2>The flow of MongoDB writes</h2>
<p>This is a very complicated subject and one which rightly deserves it’s own chapter in a book. Fortunately I haven’t written a MongoDB book, but I’m going to explain in as simple terms as I can, how the flow of how writes are sent from your client to actually be saved in your cluster.</p>
<ol>
<li>Your application server wants to update a users name, it opens a connection to one of your mongos servers and sends the write.</li>
<li>The Mongos will look inside the config servers, to work out which shard should store the information. Once the Mongos has located this information, it will send the write to the primary node in that shards replica set.</li>
<li>The write is received by the MongoDB wire protocol, this is essentially a TCP/IP socket for mongod.</li>
<li>The socket will communicate with mongod and start the journalling process, starting with the memory journal and then the disk journal, as described above.</li>
<li>Every minute (customisable) the disk journal is written to the database and oplog.</li>
<li>Secondary nodes will suck data from their source and update their oplog. This can happen at any time, depending on how busy the secondaries are.</li>
</ol>
<p>It&#8217;s a pretty complicated process and there are a bunch of configurations that can interfere with these process. On top of that you might not be using shards or replication which seriously simplifies the process. I might actually write a separate post to go over this in detail.</p>
<h2>Config Servers</h2>
<p>Config servers are required as soon as you start using shards to scale out your database. The config servers are used to store information about where you data resides in the cluster, which nodes you have in the cluster, the status of these nodes and general setting thats your mongod and mongos nodes should adhere too.</p>
<p>Your applications should ideally always have 3 config servers, to prevent data loss, each server should reside on a separate machine, however they can be low powered machines or even the application servers if you budget doesn&#8217;t stretch for separate servers. A config server is simple tailored mongod which is started with the &#8211;configsvr flag.</p>
<p><pre class="prettyprint linenums">
mongod --configsvr --dbpath /var/lib/mongodb -f /var/lib/config/mongod.conf
</pre>
<h2>Drum Roll</h2>
</p>
<p>And that&#8217;s a wrap. As I mentioned above, when I first started this series, MongoDB version 3 wasn&#8217;t released. Thankfully, despite the internals having been completely re-engineered, the consumer API has stayed almost identical. There&#8217;s probably the odd function which has been renamed or the odd parameter which has been meddled with, but I&#8217;ve gone through my old posts and updated most of them.</p>
<p>Like I said above, in time I might write up a detailed post about how the internal of writing works within MongoDB, with all the varieties of configuration and architecture. For now, the details above along with all my posts, you should be enough for the average user.</p>
<p>As always, thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-10-tips-and-final-thoughts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 9 – Deployments</title>
		<link>https://www.jakowicz.com/mongodb-part-9-deployments/</link>
				<comments>https://www.jakowicz.com/mongodb-part-9-deployments/#comments</comments>
				<pubDate>Sun, 29 Nov 2015 13:44:28 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1343</guid>
				<description><![CDATA[This is post 9 of 10 in the series &#8220;MongoDB&#8221; Welcome back. Deploying MongoDB isn&#8217;t difficult, but there are a tonne of tricks you can use to really optimise your database. That&#8217;s what were going to be covering in this post. I’m not going to be covering how to create clusters as I already covered... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-9-deployments/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 9 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>Welcome back. Deploying MongoDB isn&#8217;t difficult, but there are a tonne of tricks you can use to really optimise your database. That&#8217;s what were going to be covering in this post.</h2>
<p>I’m not going to be covering how to create clusters as I already covered that in part 5 of the series &#8211; <a href="http://www.jakowicz.com/mongodb-part-5-sharding/">Sharding</a>. I’m not even going to discuss provisioning solutions like Puppet, Chef, Ansible etc. What I am going to discuss however, is a collection of system choices that need to be thought, about when creating your cluster. So let&#8217;s get started.</p>
<p><span id="more-1343"></span></p>
<h2>Storage</h2>
<p>If your budget stretches to affording SSD’s, it&#8217;s a great investment. The hard disk is the main bottleneck in any MongoDB setup. Using SSD’s or large amounts of memory will dramatically improve IO Wait, Lock times and CPU power usage.</p>
<h2>CPU</h2>
<p>MongoDB doesn’t require much CPU power, apart from when building indexes and occasionally when using MapReduce. A dual core CPU can easily handle 10k queries per second.</p>
<h2>Operating System</h2>
<p>MongoDB should really only be deployed on a Linux distribution. As much as MongoDb is supported on Windows and OSX, you’re asking for trouble using either in production.</p>
<p>Make sure you use a 64 bit OS always, otherwise your data directory will be limited to 2GB. Mongo 3, which was released about 6 months ago, is only supported on 64 bit systems.</p>
<p>Mongod instances can be split across multiple different OS’s, every OS uses the same wire protocol and stores data in the same manner.</p>
<p>MongoDB recommend running on a little-endian architecture. Basically all modern CPU’s are little-endian or bi-endian, which means they support little-endian and big-endian.</p>
<h2>RAID setup</h2>
<p>There are a bunch different RAID setups you could use to shard and replicate your data. These aren’t really necessary as MongoDB provides a far more customisable solutions to both sharding and replication. But here are a couple of options that you might want to consider.</p>
<ol>
<li>RAID0 &#8211; Data is split across multiple hard disks, this will result in data loss if a hard disk is to crash.</li>
<li>RAID1 &#8211; Data is replicated across all hard disks on the RAID. If a hard disk crashes, there will be no data loss.</li>
<li>RAID5 &#8211; All data is replicated onto at least 2 drives, so any drive can crash and data will still be available.</li>
<li>RAID10 &#8211; This is a mix of using both RAID0 and RAID1. Originally with a RAID0 to shard files and RAID1 to replicate each RAID0.</li>
</ol>
<h2>Swap Space</h2>
<p>MongoDB doesn’t normally require swap space, but it can be useful when building indexes and running repairs. Otherwise MongoDB may get killed by the OOM killer.</p>
<p>Here are some command you can use to create and start using a swap file.</p>
<pre class="prettyprint linenums">
# create a directory that will hold the swap file 
sudo mkdir -p /var/cache/swap/

# for 4GB storage, 1MB at a time 
sudo dd if=/dev/zero of=/var/cache/swap/myswap bs=1M count=4096

# Only root can access 
sudo chmod 0600 /var/cache/swap/myswap

# Make the swap file 
sudo mkswap /var/cache/swap/myswap

# Announce to system
sudo swapon /var/cache/swap/myswap

# Insert the following line in /etc/fstab for swap from the next boot:
/var/cache/swap/myswap none swap sw 0 0

# Turn off swap space if need be
sudo swapoff /var/cache/swap/myswap
</pre>
<h2>Filesystem</h2>
<p>If possible, ext4 or XFS should be used as they allow for filesystem snapshots. ext3 is not recommended, because MongoDB regularly creates zero-fill data files, which is slow and can freeze for minutes.</p>
<h2>Memory Overcommitting</h2>
<p>This happens when a process requests more memory than is available. If overcommitting is enabled the kernel will promise the memory in the hope that it’ll become available. This doesn’t work well with MongoDB, to disable overcommitting run</p>
<pre class="prettyprint linenums">
echo 2 > /proc/sys/vm/overcommit_memory
</pre>
<h2>NUMA</h2>
<p>Turn off NUMA (Non Uniform Memory Architecture)</p>
<p>NUMA is the term meaning each CPU has its own allocated memory. This is useful for day to day work, but in a MongoDB environment, it can result in your memory not being used effectively. NUMA should be disabled in your bios and MongoDB restarted.</p>
<pre class="prettyprint linenums">
# Updating Your bios (grub.cfg)
kernel /boot/vmlinuz-2.6.38-8-generic root=/dev/sda ro quiet numa=off

# Starting mongod with the numactl command
numactl --interleave=all mongod -f config.conf
</pre>
<h2>Update your readahead</h2>
<p>Read ahead is how much extra data should read into memory which wasn’t asked for. This can be useful for gathering data which might be required soon when you have large documents. However if you have small documents, you would probably want a smaller readahead. This will stop data being read into memory, which isn’t needed.</p>
<pre class="prettyprint linenums">
# To get a report of your readahead for each drive
# The RA column is your readahead and is measure in 512 bytes sectors.
# So a value of 256, means 256 * 512 bytes = 128kb readahead
sudo blockdev --report

# Update the readahead for /de/sdb3 to 16 * 512 bytes = 8kb
sudo blockdev --setra 16 /dev/sdb3
</pre>
<p>Readahead should not be set below 16 sectors (8KB), as this will make fetching indexes less efficient. Furthermore, it’s not recommended to set the readahead above 256 sectors.</p>
<h2>Hugepages</h2>
<p>Hugepages should be disabled. It designed for systems that do a lot of sequential reading, like relational databases. Hugepages can cause similar issues to a high readahead.</p>
<p><a href="http://www.oracle-base.com/articles/linux/configuring-huge-pages-for-oracle-on-linux-64.php#disabling-transparent-hugepages" target="_blank">Learn more about how to configure hugepages</a></p>
<h2>File descriptors</h2>
<p>The maximum number of file descriptors is configured to 1024 by default. This should be increased to unlimited or at least increased to around 20,000. Each incoming and outgoing request will use a file descriptor. So a file descriptor limit of 20,000, will allow roughly 10,000 concurrent connections.</p>
<pre class="prettyprint linenums">
# Unlimited file descriptors
ulimit -m 

# 20,000 file descriptors
ulimit -n 20000
</pre>
<h2>Firewalls</h2>
<p>Make sure each MongoDB node, can only be accessed by nodes that require them.</p>
<ol>
<li>Clients can connect to each mongos</li>
<li>Mongos can connect to all mongod data nodes &#038; config nodes</li>
<li>Mongod data nodes can connect to other mongod data nodes &#038; config nodes</li>
<li>Config nodes don’t need to connect to any MongoDB nodes</li>
</ol>
<h2>Make sure clocks are in sync</h2>
<p>If the clocks on your shards are not in sync you can have issues with replication. MongoDB can deal with slight discrepancies (up to a few minutes). Clocks can be kept in sync by using the <a href="http://doc.ntp.org/" target="_blank">ntp daemon</a>.</p>
<h2>Turn off periodic updates</h2>
<p>Turn off updates from package managers which can slow down the system unexpectedly. This should be managed with a proper configuration management tool anyway.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-9-deployments/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 8 – Backups</title>
		<link>https://www.jakowicz.com/mongodb-part-8-backups/</link>
				<comments>https://www.jakowicz.com/mongodb-part-8-backups/#respond</comments>
				<pubDate>Sun, 18 Oct 2015 18:09:15 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1336</guid>
				<description><![CDATA[This is post 8 of 10 in the series &#8220;MongoDB&#8221; Far too often do backups get overlooked. In this blog, I&#8217;ll explain all the ways of backing up your MongoDB databases along with some general backup tips. Before getting into the nitty gritty of backups, it&#8217;s important to remember that there are multiple MongoDB setups... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-8-backups/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 8 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>Far too often do backups get overlooked. In this blog, I&#8217;ll explain all the ways of backing up your MongoDB databases along with some general backup tips.</h2>
<p>Before getting into the nitty gritty of backups, it&#8217;s important to remember that there are multiple MongoDB setups you could be running. For example, you could be running a standalone MongoDB instance, a replica set, or using shards. Regardless of which setup you are using, the backup process is practically identical.</p>
<p>One of the most important tips when creating backups, is to always use secondary nodes where possible. This will prevent your application from being inaccessible. If you to were backup a primary node, your application will be unable to receive writes, which is less than ideal to put it lightly.</p>
<p><span id="more-1336"></span></p>
<h2>Type of backups</h2>
<h3>Snapshots</h3>
<p>Depending on what OS and filesystem you are running, it may be possible for you to create system snapshots. This isn&#8217;t a MongoDB feature but can be accomplished using a tool called LVM on Linux. A snapshot is essentially a complete freeze frame of a file system at a certain point in time. This is easily to automate and requires zero downtime. Snapshots are also supported by Amazon&#8217;s, EBS volumes and on the Google Cloud Platform for free, allowing you to create and rollback from snapshots very quickly. Creating snapshots is said to have a O(1) complexity, which means regardless of the amount of data in the snapshot, the time to create it will remain constant. Creating snapshots on your own hardware can be more tricky, but it certainly worth the time investment.</p>
<h3>Manual Backups</h3>
<p>By manual backups, what I actually mean is backing up the directory which contains your data. It&#8217;s as simple as locking the data directory, so no further writes can be performed, copying your data directory to a backup location and then releasing the lock. It&#8217;s important to note that when locking the data directory, writes to all databases will be locked, not just writes to the database you are backing up. This is why backups should only be made on secondaries. If you&#8217;re running MongoDB on a single node without replication, you are unfortunately going to have some downtime while this happens.</p>
<pre class="prettyprint linenums">
// Locks all databases
db.fsyncLock()

// Copy data to a backup location
cp /data/db/* /backup

// Release database locks
db.fsyncUnlock()
</pre>
<p>To restore from a backup, you can follow this same process. Just copying data from your backup location to your mongo data location instead.</p>
<h3>Mongodump and mongorestore</h3>
<p>MongoDB has also provided two tool for you to backup and restore data, aptly names mongodump and mongorestore. Mongodump is slower than manual backups but also more customisable. There is no need to shut down your mongod instance or create any locks for this to work. Simply run mongodump and all of your databases will be dumped into a directory named dump, at your current location.</p>
<pre class="prettyprint linenums">
// The --oplog flag will make sure all operations that happen during the backup are replayed.
mongodump -p 27017 --oplog

// --oplogReplay must be used when --oplog flag is used in the mongodump
mongorestore -p 27017 --oplogReplay dump_dir

// It's also possible to just restore a specific collection into a specific db.
mongorestore --db newDb --collection coll dump/db/coll.bson
</pre>
<p>When a replica set member is being restored via mongorestore, the oplog collection must also be restored. Without the oplog collection, MongoDB will not know which version the node is on and what still needs migrating from the other nodes.</p>
<pre class="prettyprint linenums">
use local
db.createCollection("oplog.rs", {"capped" : true, "size" : 10000000})
mongorestore -d local -c oplog.rs dump/oplog.bson
</pre>
<p>The same version of mongodump and mongorestore should be used to avoid compatibility issues.</p>
<h3>Delayed secondary</h3>
<p>As I mentioned in the replica set post, it&#8217;s possible to create delayed secondary nodes, these are nodes which never serve reads or writes and always stay a certain amount of writes behind the primary node. This ensures that if your other nodes get corrupted. You&#8217;ll still have a relatively recent backup of the data. For more information on setting up delayed secondaries, check out the post I wrote on <a href="/mongodb-part-4-replication/">replication</a>.</p>
<h3>Backup shards</h3>
<p>Backing up shards can be tricky business, if you have the option, definitely go down the snapshotting route. It&#8217;s by far the best way to ensure there is no data loss.</p>
<p>Shards are also backed up just like standalone nodes and replica sets. This makes sense as that&#8217;s all a shard is anyway. Just you now have multiple shards, which are probably  replica sets in their own right. So what&#8217;s the problem. You can freeze one secondary in each replica at the same time and perform a manual backup or mongodump. This will give you an exact version of the data set at a specific point in time for all your shards. But there&#8217;s a problem!</p>
<p>Let&#8217;s assume, that you make backups every night at midnight. 8pm hits, 20 hours after your last backup and one of your shards vanishes off the grid. The warehouse burnt down. Shit.</p>
<p>You think you&#8217;re safe, but actually in the last 20 hours, any number of chunks could have moved on and off off that shard. What this means is some data which you think you&#8217;ve lost may have moved to another shard and some data you think was safe has moved to the missing shard. This means when recovering the 20 hour backup, you&#8217;re going to lose some data, unless no chunks have moved onto the node in the last 20 hours. Obviously you could look at the chunk movement logs, but it&#8217;ll be incredibly tedious and will no doubt result in some down time and lots of dev time wasted. This is why snapshotting is a better choice.</p>
<p>Another option is to permanently have the balancer off and manually balance your shards, which will prevent chunks from moving around automatically. I highly recommend this if you can’t use a snapshot backup approach.</p>
<p>Whatever approach you take, when performing a backup of a shard, you should first turn off the balancer, to prevent chunk moving around mid backup.</p>
<pre class="prettyprint linenums">
// Run from each mongos node to disable the balancer
sh.setBalancerState(false)
</pre>
<p>You can then continue to perform the normal backup procedure described above; Manual backups or mongodump. Don&#8217;t forget to backup the oplog too when using mongodump.</p>
<p>When backing up a shard you also need to make sure you backup one of your config databases using the command:</p>
<pre class="prettyprint linenums">
mongodump --oplog --db config
</pre>
<p>Without the config database, you will lose critical data, like which chunks reside on what shards. Lastly you need to re-enable the balancer on each mongos:</p>
<pre class="prettyprint linenums">
sh.setBalancerState(true)
</pre>
<h2>Conclusion</h2>
<p>If you&#8217;re using MongoDB, than you&#8217;re probably using shards too. If you&#8217;re using shards than you almost definitely want to make backups using snapshots. Either way backups are relatively simple and there’s no excuse for not setting them up immediately. Thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-8-backups/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 7 – MapReduce</title>
		<link>https://www.jakowicz.com/mongodb-part-7-mapreduce/</link>
				<comments>https://www.jakowicz.com/mongodb-part-7-mapreduce/#respond</comments>
				<pubDate>Sun, 14 Jun 2015 21:23:29 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MapReduce]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1304</guid>
				<description><![CDATA[This is post 7 of 10 in the series &#8220;MongoDB&#8221; MapReduce is a multi-step programming paradigm, which has been around for 2 decades. The goal of MapReduce is to break down a collection of data, sometimes from different machines on a network. Executing MapReduce jobs in parallel, over multiple machines, will significantly improve processing times.... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-7-mapreduce/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 7 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>MapReduce is a multi-step programming paradigm, which has been around for 2 decades. The goal of MapReduce is to break down a collection of data, sometimes from different machines on a network. Executing MapReduce jobs in parallel, over multiple machines, will significantly improve processing times.</h2>
<p>The concept of MapReduce is inspired by the map and reduce functions in functional programming. When MapReduce was defined, it was as a 3 step process (Map, Shuffle, Reduce), MongoDB have taken this one step further and added a finaliser step. So lets see what’s involved in each step.</p>
<p><span id="more-1304"></span></p>
<h2>MapReduce Steps</h2>
<p><b>Map</b> &#8211; Maps every document in a collection with a key, value pair. What this means is, each document in a collection will be run through a map function individually and a new form of document should be emitted. This could be as simple as passing a document into a map function and multiplying a score value by 10. Think of map as being map one document to another document. Each document which is emitted should also have a key, which will be used in the shuffle and reduce steps.</p>
<p><b>Shuffle</b> &#8211; this takes the documents returned from the map step and aggregate them by their key, this assures each key has a single record which is mapped to multiple emitted values. This is done entirely in the background.</p>
<p><b>Reduce</b> &#8211; This step is used to break down the results of the shuffle step. The reduce function is run for every key that was emitted from the shuffle step. The reduce function is also passed a collection of the emitted values to aggregate.</p>
<p><b>Finaliser</b> &#8211; This is a final step, it will receive the output from the reduce step and perform one further reduce on it before returning the response to the client. This step is optional.</p>
<h2>Using MapReduce</h2>
<p>Using MapReduce is actually pretty simple, you need to define your map, reduce and maybe finalise functions and then execute them using the runCommand method.</p>
<pre class="prettyprint linenums">
db.runCommand({"mapreduce" : "collectionName", "map" : mapFunction, "reduce" : reduceFunction})
</pre>
<h2>Example MapReduce</h2>
<p>Search all documents in a collection and find every field name being used.</p>
<pre class="prettyprint linenums">
// This map is called for each document in the collection
map = function() {
    // Loop over each field in the collection
    for (var key in this) {
        // For each field, emit is called with the field name as the key and {count : 1} as the value.
        emit(key, {count : 1});
    }
};

// This is run for every field name that the map function found.
// key = field name, emit = A collection of {count : 1} objects
reduce = function(key, emits) {
    total = 0;
    for (var i in emits) {
        total += emits[i].count;
    }
    return {"count" : total};
}

// This outputs a bunch of information about, if the MapReduce was successful, a  collection name, where the result can be found, among other things.
db.runCommand({"mapreduce" : "collectionName", "map" : map, "reduce" : reduce})
</pre>
<h2>MapReduce Keys</h2>
<p>When running MapReduce jobs it can be useful to pass along additional keys, other than map and reduce, below are so of the most useful keys:</p>
<p><b>finalize</b> &#8211; This takes a function with the signature finalize(prev). This is called for each value returned by the reduce function, it can be used to further reduce the response.</p>
<p><b>keeptemp</b> &#8211; Takes a boolean value. Should the collection containing the response be kept, by default it will be removed when the connection is closed.</p>
<p><b>out</b> &#8211; The name of the collection, where the response should be saved. Setting this key, will automatically set keeptemp to true.</p>
<p><b>query</b> &#8211; Takes an object literal of criteria for data selection e.g. { “name” : “simon” }</p>
<p><b>limit</b> &#8211; The amount of documents you want to select.</p>
<h2>MapReduce Tips</h2>
<p>The output from a maps emit, must be the same as the response from a reduce. This way the output from 1 reduce step can be sent into another reduce step.</p>
<p>MapReduce is slow and should not be used with real time data</p>
<h2>Aggregation functions</h2>
<pre class="prettyprint linenums">
// Total documents in a collection
db.collection.count()

// Get every distinct age in the users collection
db.runCommand({"distinct" : "users", "key" : "age"})
</pre>
<h2>Conclusion</h2>
<p>MapReduce is a powerful very powerful concept within computer science. There are books devoted to just this subject and the fact that it&#8217;s still around after 20 years proves its credibility. Just be careful not to get stuck in the one size fits all trap also aptly named the golden hammer antipattern. MongoDB is a great all round database, but MapReduce isn&#8217;t its strongest feature. If crunching huge amounts of data is what your doing, you may be better off using Apache Hadoop or something similar.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-7-mapreduce/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 6 – GridFS</title>
		<link>https://www.jakowicz.com/mongodb-part-6-gridfs/</link>
				<comments>https://www.jakowicz.com/mongodb-part-6-gridfs/#respond</comments>
				<pubDate>Sun, 17 May 2015 13:40:48 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[GridFS]]></category>
		<category><![CDATA[Mongo]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1299</guid>
				<description><![CDATA[This is post 6 of 10 in the series &#8220;MongoDB&#8221; If you could have a wild guess at what GridFS is used for, you’d probably say some kind of file system and you wouldn’t be completely wrong. On the contrary, GridFS isn’t actually a filesystem, but rather a convention for storing large binary data files... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-6-gridfs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 6 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>If you could have a wild guess at what GridFS is used for, you’d probably say some kind of file system and you wouldn’t be completely wrong. On the contrary, GridFS isn’t actually a filesystem, but rather a convention for storing large binary data files inside MongoDB.</h2>
<p>I haven’t covered storing binary data in MongoDB yet, however it&#8217;s possible to store binary data in standard documents, without using GridFS at all. This is possible using the BSON type BinData. It’s not very well supported by the mongo client, however most language drivers have good support, just google “MongoDB <language> BinData”. This is all well and good, in fact if you’re storing under 16MB of data per file, it’s recommended to use this approach. If however you are storing binary files larger than 16MB, GridFS is the way to go. 16MB is the maximum size of a document in MongoDB.</language></p>
<p><span id="more-1299"></span></p>
<h2>GridFS Intro</h2>
<p>By using GridFS, your binary files will automatically be broken up into smaller chunks which can be examined individually. This means there will be 2 collections, one to store the actual chunks and one to store the metadata which states which chunks relate to one another. These collections are named <a href="http://docs.mongodb.org/manual/reference/gridfs/#gridfs-chunks-collection">fs.chunks</a> and <a href="http://docs.mongodb.org/manual/reference/gridfs/#gridfs-files-collection">fs.files</a> respectively.</p>
<h2>Sharding</h2>
<p>In most situations, you&#8217;re probably not going to need to shard your binary files. However if you do, you&#8217;re going to want to shard using the files_id field on the fs.chunks collection. Doing so will make sure all chunks of the same file are stored on the same shard.</p>
<p>Be carful not to mix up shard chunks and GridFS chunks. Shard chunks are small collections of documents which all reside on a single shard. GridFS chunks are basically a single chunk of binary data that makes up part of a larger file.</p>
<h2>Replication</h2>
<p>You might be thinking, how does replication fit into this new data type. Well, actually it works just like any other data you have stored in documents. As long as you have nodes connected via a replica set, MongoDB will automatically replicate your binary data, just like it replicate everything else.</p>
<h2>Mongofiles</h2>
<p>In part one, I wrote about how MongoDB follows the unix philosophy of creating small tools that do one thing and do it well. Well on that note, when you install MongoDB, another tool you&#8217;ll get is called mongofiles. This tool is super simple to use and allows you to easily copy binary files into your database. Mongofiles generally takes most of the flags that the mongod tool uses, for example using flags like &#8211;hostname to connect to a specific host, or &#8211;port to connect to a specific port. You must also provide a -d flag which tells mongofiles the database you want to store these binary files in.</p>
<p>Here are some example mongofiles command</p>
<pre class="prettyprint linenums">
// Upload the foo.txt file to the reporting database
mongofiles -d reporting put foo.txt

// List all files in the reporting database
mongofiles list

// Download the foo.txt file from the reporting database
mongofiles get foo.txt

// Delete the foo.txt file from the reporting database
mongofiles delete foo.txt
</pre>
<h2>Conclusion</h2>
<p>It feels good to have such a short but sweet MongoDB blog, but that pretty much covers what you need to know. Make sure you can differentiate between shard and GridFS chunks as they are very different things. Most languages that you would dream of programming in, have support for using GridFS too, making it really easy to get started with. Until next time, where I&#8217;ll be discussing all things Map Reduce.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-6-gridfs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>MongoDB – Part 5 – Sharding</title>
		<link>https://www.jakowicz.com/mongodb-part-5-sharding/</link>
				<comments>https://www.jakowicz.com/mongodb-part-5-sharding/#respond</comments>
				<pubDate>Tue, 05 May 2015 22:34:41 +0000</pubDate>
		<dc:creator><![CDATA[Simon]]></dc:creator>
				<category><![CDATA[Document Databases]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[NoSQL]]></category>
		<category><![CDATA[Chunks]]></category>
		<category><![CDATA[mongo config]]></category>
		<category><![CDATA[mongod]]></category>
		<category><![CDATA[mongos]]></category>
		<category><![CDATA[Scaling]]></category>
		<category><![CDATA[shard keys]]></category>
		<category><![CDATA[Sharding]]></category>

		<guid isPermaLink="false">http://www.jakowicz.com/?p=1285</guid>
				<description><![CDATA[This is post 5 of 10 in the series &#8220;MongoDB&#8221; Sharding, the art of scalability. That’s a bold statement, after all, there are two very important arts to scalability. What shards allow you to do however, is to scale out. What this means is, you no longer need to keep all of your data on... <a class="more-link" href="https://www.jakowicz.com/mongodb-part-5-sharding/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<aside class="wp-post-series-box series-mongo-series">
<p class="wp-post-series-name">
		This is post 5 of 10 in the series <em>&ldquo;MongoDB&rdquo;</em>	</p>
</aside>
<h2>Sharding, the art of scalability. That’s a bold statement, after all, there are two very important arts to scalability. What shards allow you to do however, is to scale out. What this means is, you no longer need to keep all of your data on one hard drive or machine, heck not even in the same warehouse or continent. You can have unlimited machines in unlimited geographic locations, connected together and serving data as if it was all the data was stored in one central location.</h2>
<p>If you’re not already familiar with the terms scaling up/vertically and scaling out/horizontally, carry on reading. Otherwise you can skip the next few paragraphs.</p>
<p><span id="more-1285"></span></p>
<h2>Scaling Up/Vertically</h2>
<p>Scaling up is a concept, which is purely hardware based, You don’t need to modify the way in which you use your software. All you have to do is beef up your machine e.g. Throw in a swanky new SSD, an octuple core CPU and some extra memory and you’ll be scaling up like a seasoned professional.</p>
<p>tl;dr: Scaling up means beefing up your existing nodes.</p>
<h2>Scaling Out/Horizontally</h2>
<p>Scaling out on the other hand, is a completely different ball game. Irrespective of what DBMS you are using, you have to make some changes to your architecture to achieve scaling out. Scaling out in MongoDB is known as sharding, what sharding allows you to do, is split chunks of data across an unlimited number of nodes, over a network.</p>
<p>tl;dr: Scaling out means adding more nodes to share the load.</p>
<h2>Sharding 101</h2>
<p>Up until now, in this crash course of MongoDB, all we have used is mongod. Before we can start using shards, we need to add two new mongo tools to our toolbox: mongos (mongo shard) and another type of mongod for config servers.</p>
<p>Until I get onto what exactly a shard is in its full glory. Just think of a shard as either a single node or a replica set which stores data. If you have one shard, it will contain 100% of the data set. If you have two shards, the data will be split across both, what data gets saved on which shards is customisable, so data won&#8217;t necessarily be split 50:50.</p>
<p>In the below section I’m going to detail the basics of starting a mongo shard, using 3 config servers and a single shard, the shard will consist of a replica set of 2 nodes. There are a few steps here, so lets break it all down:</p>
<ol>
<li>Start 3 mongod config instances.</li>
<li>Start a mongos instance, and tell it where to find each config server.</li>
<li>Start 2 mongod nodes and create a replica from them.</li>
<li>Connect to the mongos and add the replica set as a shard.</li>
<li>Read that one more time, it&#8217;s important you understand it fully.</li>
</ol>
<h3>Step 1: Start Config servers</h3>
<p>Config servers are used to store shard metadata, like what mongo shards exist, which locks are on which databases, which shards contain what chunks, which nodes contain what data, among other things.</p>
<p>Mongod config servers are standard mongod instances which are started with the &#8211;configsrv flag. Config servers by default run on port 27019 and their data resides in /data/configdb. These can both be changed with the &#8211;port and &#8211;dbpath flags respectively. You should have 3 config servers running on different machines in production environments at all times. On non-production environments, it’s safe to have all 3 mongod config servers running on the same machine. Whether or not the mongod config servers are on the the same machine or not, they must all be able to communicate with each other, so make sure your firewall is appropriately configured.</p>
<pre class="prettyprint linenums">
mongod --configsvr --dbpath /data/configdb1 --port 27019
mongod --configsvr --dbpath /data/configdb2 --port 27020
mongod --configsvr --dbpath /data/configdb3 --port 27021
</pre>
<h3>Step 2: Start Mongos instances</h3>
<p>Mongos instances as you probably guessed, stands for mongo shard. However that&#8217;s a little misleading. Your shards are the actual data nodes &#8211; the mongod data nodes. Mongos does not store any of your data, all it does is route requests to your data nodes, sort of like a load balancer, there is one huge gaping difference though. Load balancers attempt to evenly distribute read and write loads, mongos does not. Mongos will only distribute reads loads, to the nodes which contain the data you require. For writes it will send the request to the node where your configuration states the data should be stored. You can completely configure where different chunks of data should be stored by creating shard tags. I&#8217;ll cover both tags and chunks below.</p>
<p>When starting a mongos instance, a complete set of config servers should be provided. Lets assume all of the config servers and mongos instances are started on localhost. We would start a mongos by running:</p>
<pre class="prettyprint linenums">
mongos --configdb localhost:27019,localhost:27020,localhost:27021 --port 17022
</pre>
<h3>Step 3: Start 2 Mongod nodes in a replica set</h3>
<p>Please see my <a href="/mongodb-part-4-replication">Mongo Replication article</a>, to find out how to start a replica set. For the purpose of this article I&#8217;m going to assume both mongod instances are started on localhost using ports 27017 and 27018 and the replica set is named rs0 using the &#8211;replSet flag.</p>
<h3>Step 4: Add replica set as a shard</h3>
<p>The final step is to add the replica set you just created, as a shard. This is done by connecting to our mongos instance using the mongo binary and executing the sh.addShard() method. If you have multiple mongos instances, you only need to run the below on one of them. The change will automatically propagate via the config servers.</p>
<pre class="prettyprint linenums">
// connect to our mongos
mongo --host localhost --port 27022

// Add the two nodes from a replica set as a shard.
db.runCommand({ addShard: "rs0/localhost:27017, localhost:27018", name: "shard_name" });
</pre>
<p>As i mentioned above, you could add a single node as a shard too, by running:</p>
<pre class="prettyprint linenums">
db.runCommand({ addShard: "localhost:27017", name: "shard_name" });
</pre>
<p>The shard name is important, we’ll use this later.</p>
<p>Despite single node shards being possible, you’re better of using a replica set always, even if you only have one node in the set. Otherwise if you decide to use a replica set in the future, it&#8217;s going to be a pain in the ass.</p>
<h2>Enabling sharding</h2>
<p>You’re probably thinking, that after getting this far, surely sharding is now enabled. But you would be wrong. What you&#8217;ve actually done is merely created a shard and told it which replica set to use for CRUD. Shards can contain numerous databases, each with multiple collections. The next logical step is to enable sharding on the databases we want to shard. Connect to any of your mongos nodes and run the following:</p>
<pre class="prettyprint linenums">
sh.enableSharding("&lt;database&gt;")
</pre>
<p>Next you need to decide how you want to shard your collections. This is where the real magic happens, collections are the things which actually contain data after all. By sharding a collection, what you are saying is to split the data in that collection across multiple replica sets. Doing so allows you to scale out.</p>
<p>Sharding a collection, takes a little more thought than sharding a database. What I mean by this, is that you need to decide which fields you want to shard on, or split on if you will. You can shard by any number of fields and by any fields you want.</p>
<p>When choosing which field or fields to shard on, you want to make sure related documents are stored on the same shards. A example of this could be storing records by region. Assume you was building a small social network. It might make sense to store all users from Europe on one shard and all users from Asia on another shard. The benefit here would be that most users in Europe would have friends in Europe, so when getting a list of friends, most of the time only one shard would have to be queried. If more than one shard needs to be queried, this will happen for you automatically, however you should try to limit these queries.</p>
<p>You can think of shard key internals like indexes, after all for a shard key to exist, the same key must first exist as an index. If the index doesn’t already exist when a collection is sharded, the index will be created automatically.</p>
<pre class="prettyprint linenums">
// Shard on the region field on the user collections.
// So if the values were either Europe, Asia, N America, S America, Africa, Australia, Antarctica.
// This shard would make sure all users with the same region are stored on the same replica set
sh.shardCollection(“db.users”, { region: 1 })

// Shard on two columns: region and language.
// This would make sure all users with the same region and language are stored on the same replica set
sh.shardCollection(“db.user”, { region: 1, language: 1})
</pre>
<p>It&#8217;s always best to have shard keys with a high cardinality.</p>
<h2>Shard Tags</h2>
<p>In the above “Sharding 101” section, I mentioned tags on a few occasions, but I’ve not gone any further than that. What I did cover, was how to shard collections. What you can’t do when initially sharding a collection, is decide which documents should be saved in which replica sets. This is where tags come in.</p>
<p>Tags allow you to get around this by first assigning tags to your shards and then assigning tags to field values or ranges, mongos will use these tags to decide where to write and read data from.</p>
<p>That sounds bloody confusing I know, so here&#8217;s an example:</p>
<p>Lets assume you have a collection called profiles, which contains a field called rank. The lower the rank, the more popular the profile is and the more often it is viewed. Lets assume that the collection has already been sharded on the rank field. You have 2 shards one which uses spinning disks and one that uses SSD’s. It would make sense to always store the most popular records on SSD, so they can be fetched quicker. Lets do that:</p>
<pre class="prettyprint linenums">
// Add a tag called ssd to the shard called ssd_shard_name. 
// Remeber, the shard name was decided when the shard was created.
sh.addShardTag(“ssd_shard_name”, “ssd”)

// Add all records with a rank between 1 and 100 to any shard with an ssd tag
sh.addTagRange(“db.profiles”, { “rank”: 1 }, { “rank”: 100 }, “ssd”)
</pre>
<p>If tags are changed on a shard, documents which no longer match the tags will automatically be migrated to a shard that do. If no nodes support them, they will not move.</p>
<pre class="prettyprint linenums">
// If you want to make sure all documents are saved to a specific shard, you can use the MinKey and MaxKey values
sh.addTagRange(“db.profiles”, { “rank”: MinKey }, { “rank”: MaxKey }, “ssd”)
</pre>
<h2>Chunks</h2>
<h3>What Are chunks</h3>
<p>Chunks are another topic I’ve mentioned and they’re another very important aspect of sharding. Chunks are exactly what they say on the tin &#8211; a chunk of a shard. Lets go back to the example above, where we created a shard key on the user collection and the region and language fields:</p>
<pre class="prettyprint linenums">
sh.shardCollection(“db.user”, { region: 1, language: 1 });
</pre>
<p>I said above, that this shard key will mean every document with the same region and language will reside on the same replica set. That is true, but we can actually go a little more granular. What it actually confirms, is the documents will reside on the same chunk.</p>
<p>Generally each shard key should have a very high cardinality or even better, be completely unique. Chunks don’t just contain identical values though, they group data by ranges (numerically or alphabetically). Lets assume you have 2 regions and 10 languages. That means there are 20 different permutations of shard key and therefore a maximum of 20 chunks can be created. That isn&#8217;t really ideal, as I mentioned above. Share keys should have a high cardinality or be unique. With only 20 possible permutations of shard key, there is the potential for chunks to grow huge because they cannot be broken down any further. This will make it difficult to scale out.</p>
<p>Also just because there is a maximum of 20 chunks, it doesn’t mean there will be 20 chunks. In fact to begin with there will be only 1 chunk and as you data set grows, your mongos daemons will try to split the chunks to make them smaller. If shard keys are unique or have a high cardinality, it means the mongos daemons will easily be able to break down chunks.</p>
<h3>How are chunks created?</h3>
<p>As soon as you start using shards, you no longer send reads and writes to individual nodes. Instead you connect to a mongos and the mongos sends the request to the correct shards. When you send the first write to a collection on each shard, the mongos will create a brand new chunk. All further writes will then be part of that chunk. Each mongos will individually keep track of how big chunks are getting on each shard. After receiving a certain number of writes, the mongos will ask the mongod to try and split the chunks into smaller chunks. The mongod will return a bunch of split points to the mongos and the mongos will then send the new chunk ranges to the config servers for saving. No data is moved at this point just chunks are broken down, so you have smaller and more manageable sets of data.</p>
<p>Chunks are automatically evenly distributed across all of your shards, unless you have tags setup to store them differently. If you remove shard tags, the mongos nodes will slowly try to move chunks between shards to evenly distribute them.</p>
<h3>Chunks and config servers?</h3>
<p>When a chunk is split into multiple smaller chunks, data isn’t actually moved. All that happens, is the config servers which store the different chunk ranges updates itself, to represent the new chunk ranges.</p>
<p>For a chunk to be split successfully, all config servers must be online and accessible. If a config server isn&#8217;t available, a split will be attempted after each write request to a mongos which has reached its threshold.</p>
<p>The amount of writes a mongos has to receives, before it asks the mongods to provide split points will vary. It depends mainly on the size of your collections. Unfortunately this value isn&#8217;t customisable.</p>
<h3>Balancing rounds</h3>
<p>A balancing round is when a mongos checks its threshold to see if it needs to ask the shards for split points in its chunks. Any mongos can run a balancing round, but only one mongos can run it at a time.</p>
<p>When a mongos becomes the balancer, it will create a balancer lock on the config database. The lock will stop other mongos nodes from becoming the balancer until the lock is freed. The lock is created on the config servers db.locks collection.</p>
<p>The balancer not only breaks down chunks, but can also move chunks between shards. Chunks will remain on the original shard and will continue to be served from the original shard until the chunk has been fully migrated. Once migrated mongos may try to route reads to the old shard for a while, this will silently fail and automatically route the request to the correct shard.</p>
<h3>Jumbo chunks</h3>
<p>If on one of your config servers you run:</p>
<pre class="prettyprint linenums">
db.settings.find({ _id: "chunksize" });
</pre>
<p>You’ll get a number, which is the maximum size of a chunk in megabytes, once a chunk exceed this size, it can no longer be split or moved without manual processes. These chunks are called jumbo chunks. A good chunk size is no bigger than 64MB. Having reasonably large chunks, will prevent your mongos nodes from constant splitting and moving of chunks around. If you decrease the chunk size. The chunks will not be split straight away. However when they are split they will trend towards the new size.</p>
<h4>Splitting and moving jumbo chunks</h4>
<p>You cannot split chunks which are greater than the max chunk size, without temporarily increasing max chunk size, or manually splitting a chunk using sh.splitAt() e.g.</p>
<pre class="prettyprint linenums">
sh.splitAt("db.users", {"user_id": 1234})
</pre>
<p>This will split the chunk containing the user with the user_id of 1234.</p>
<p>Jumbo chunks cannot be moved without increasing the chunk size, turning of the balancer and manually moving them.</p>
<pre class="prettyprint linenums">
// Turn of the balancer for the users collection
sh.disableBalancing(‘users’)

// Move the chunk containing the user with the user_id 1234, to the shard named shard2.
sh.moveChunk("db.users", { user_id: 1234 }, "shard2")
</pre>
<h2>Shard Keys</h2>
<p>When choose your shard keys, you want to carefully think about who is going to be primarily accessing the data and always trying to minimise the amount of shards required to perform an operation. Here are a couple of shard key types you could use:</p>
<h3>Ascending</h3>
<p>These use a field like _id that constantly gets larger. This means one shard gets all initial writes and are then chunked and moved, which is less than ideal in most situations, unless you&#8217;re attempting the firehose strategy.</p>
<h3>Randomly distributed</h3>
<p>These use fields, where data is inserted in no particular order e.g. email address, name, age. Randomly distributed fields are evenly(ish) distributed. MongoDB claims to not be as efficient accessing randomly distributed chunks. These are a very common choice.</p>
<h3>Location based</h3>
<p>These use a field like location or ip. This helps to keep records from similar regions, in the same chunks.</p>
<h2>Final Tips</h2>
<ol>
<li>Shard keys cannot contain arrays as each value in an array is individually indexed and so the values could reside on different shards and this can&#8217;t be stored in config.</li>
<li>Chunks are not physically grouped on disk just in metadata.</li>
<li>Shard keys cannot be geospatial indexes.</li>
<li>Shard keys should always have a high cardinality, this prevents jumbo junks. Smaller chunks are easier to move around and improves load balancing. A good way of increasing cardinality is using compound keys.</li>
<li>Once inserted, to change a shard key, the documents must be dropped and re-added.</li>
<li>There is a strategy called the firehose strategy, this is the process of sending all writes to a powerful shard, then moving the chunk afterwards.</li>
</ol>
<h2>Conclusion</h2>
<p>Three cheers, you made it. That was a lot to take in. You probably have a lot of questions and a lot of uncertainties about what you&#8217;ve just read. As always I&#8217;m more than happy to answer those question. Alternatively the MongoDB site will be able to expand further on all of the above. Thanks for reading.</p>
]]></content:encoded>
							<wfw:commentRss>https://www.jakowicz.com/mongodb-part-5-sharding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
	</channel>
</rss>
