This Month in Continuous Delivery: Dev9's Top 5

As August comes to a close, we'd like to share some of the helpful articles and posts we've come across this month. Here are our top 5 Continuous Delivery and DevOps news for August:

Is Your Organizational Culture Ready for DevOps?:  http://DevOpsGuys Blog

Testing in a Continuous Delivery world: SDTimes

Balancing Quality and Velocity in Agile: InfoQ

A/B Testing + Continuous Delivery = Everyday Product Launches: InfoQ

Continuous Delivery Vs. Continuous Deployment: What's the Diff?: Puppet Labs

Enjoy, and see you next month!

Smarter Acceptance Testing with Personas

A while back, I gave a talk on the combination of Cucumber, PhantomJS, and WebDriver. There is a project on GitHub that contains the sample code. This is a small follow-up to that talk with the idea of how to manage your Cucumber scripts.

Writing BDD

To make the best use of BDD, you should write very rich steps. This is entirely the point of using behavior frameworks. In fact, if your BDD scenarios can't be used as documentation, you've done something wrong. I'm going to assume a knowledge of the Given/When/Then structure. Let's take a look at a bad example:

Scenario: User Signup
  Given A user is signing up for our site,
  When he enters his First Name,
   And enters his Last Name,
   And enters his Email,
   And re-enters his Email,
   And enters a new Password,
   And specifies his Gender,
   And enters his Birthday,
   And submits his request,
  Then an account is created,
   And account name is set as the email address.
   And a confirmation email is sent to Fred.

Now, this would be fine, but we're basically writing a bunch of steps that are quite fine-grained. Compare with something like this:

Scenario: User Signup
  Given A user is signing up for our site
    And the form is filled out correctly 
  When he submits his request
  Then an account is created
   And a confirmation email is sent.

Remember, the point of BDD stuff is to make it closer to how you would describe it when talking to somebody. You won't list out every single field when you're talking about it, so make your code-behind more powerful!

Test Data

The biggest chronic problem with testing of any sorts is test data. That is, to fully exercise a complex system, you need your data in a known state, and you need it to be consistent. Creating this data is difficult enough. A tool like Flyway can assist with setup/teardown/reset of data. But there's another problem: How do we know what pre-canned test data set to use? With enough test cases and enough scenarios to exercise, it can be difficult to remember the exact configuration of the test data. Or, if you are writing a test that uses a data set that is 99% correct, even changing that 1% can break other tests that were relying on that data to be fixed. So how do we deal with this?

In the BDD world, we have a fascinating option. Remember way back when we were all getting on board the Agile/Scrum train? The proper procedure is to write user stories in a manner like so:

As a non-administrative user, I want to modify my own schedules but not the schedules of other users.

This could be translated directly into gherkin:

Scenario: Schedule Management - User
  Given a non-administrative user
  When I attempt to modify my calendar
  Then the modification is successful

Scenario: Schedule Management - Admin
  Given a non-administrative user
  When I attempt to modify another user's calendar
  Then the modification is not successful

This looks fine, but "non-administrative user" is quite vague. And what happens when other people want to use code like that? How can we make this more extensible without sacrificing readability or maintainability? Enter personas.


The user story from above is the classic way most of us were taught to write user stories. However, when Agile was still young, the idea of personas was quite popular. From this site, we can see:

A persona [...] defines an archetypical user of a system, an example of the kind of person who would interact with it. [P]ersonas represent fictitious people which are based on your knowledge of real users.

Personas are different [from actors] because they describe an archetypical instance of an actor. In a use case model we would have a Customer actor, yet with personas we would instead describe several different types of customers to help bring the idea to life.

It is quite common to see a page or two of documentation written for each persona. The goal is to bring your users to life by developing personas with real names, personalities, motivations, and often even a photo. In other words, a good persona is highly personalized.

This is actually a very powerful construct in our BDD world. Instead of generically referring to "a user" or "an admin," we can refer to personas. Let's take that signup example again, but apply a persona:

Scenario: User Signup
  Given Fred Jacobsen is signing up for our site
    And the form is filled out correctly 
  When he submits his request
  Then an account is created
    And a confirmation email is sent.

Not very different, right? But behind the scenes can be a different story. Let's look at what it might have looked like before:

Given /^A user is singing up for our site$/ do
  user = find_user(admin: no, valid: true, ...)

Compare to:

Given /^(\w+) is signing up for our site$/ do |name|
  user = user_lookup(name)

In the first case, you need to search for a user. If the data changes underneath you, this function may not return the same result every time. In the second case, however, a user lookup by name will return you a consistent entry. Let's take a look at the Schedule Management example again, but with Personas:

Scenario: John can change his own schedule
  Given John Doe is using our app
  When John attempts to modify his calendar
  Then the modification is successful

Scenario: John cannot change Jane's schedule
  Given John Doe is using our app
  When I attempt to modify Jane Smith's schedule
  Then the modification is not successful

Again, we can look the users up by name here. But we can also have some documents behind the scenes explaining the personas. For this example, I'm going to use markdown:

# John Doe #
John Doe is a paying, non-administrative user on our site. He is a 40 year old dad of 2 boys and 1 girl, and uses our product to manage the children's activities between him and his wife, Heather Doe. He checks his schedule each morning and each evening, but does not check it throughout the day. 

## Payment Information ##
John has a monthly subscription, and is up-to-date on payments. 

## Account Setup ##
John has an avatar image and a verified email address. He has not entered his phone number for SMS updates

This gives us a wealth of information. We know that John is an active member, with up-to-date payments, has an avatar, has a verified email, and doesn't have a phone number. So the test data behind this -- what if we were smart about the way we used Flyway to manage it as well?

file: flyway/personas/001-John_Doe.sql

insert into users(name, email) values ('John Doe', '');
@id = select last_inserted_id(); /* or whatever your database supports */
insert into accounts(user_id, status) values (@id, 'active');
insert into profile(user_id, avatar) values (@id, '/images/avatars/johndoe.png');

Now we can have a 1:1 correspondence between a persona and the data that powers it. Say somebody comes along and basically wants everything John Doe has, except he wants somebody with a phone number entered? Instead of modifying John or trying to figure out if other tests will break, we just create a new user and persona:

file: flyway/personas/002-Jenny_Smith.sql

insert into users(name, email) values ('Jenny Smith', '');
@id = select last_inserted_id(); /* or whatever your database supports */
insert into accounts(user_id, status) values (@id, 'active');
insert into profile(user_id, avatar, phone) values (@id, '/images/avatars/jennysmith.png', '555-867-5309');

Moving Forward

So what have we done, really? From an abstract sense, we've created named collections of test data. They should (and ought to) be immutable. Any change that developers want to make results in a new persona. If we decide a persona is no longer useful, it also makes an easy search through your code to find all usages. Given this setup, it's a small leap to creating very complex setup:

file: resources/personas/

# Nevill Wadsworth III #
Nevill comes from an old-money family with assets in the tens of millions of dollars. He manages 5 family trusts, and uses our trading system to manage all of their assets. 

## Payment Information ##
Nevill is up-to-date on payments. Payments are deducted automatically via ACH. 

## Account Info ##
The 5 trusts that Nevill manages: 

### Trust 1: Wadsworth Unlimited ###
Wadsworth Unlimited is a small trust with the stocks of 2 companies. This is the dividend account for him. The stocks in this account are: 

  stock |    qty  | purchase price | purchase date
  MSFT  | 150,000 |         $27.45 | 10/23/1997
  BRK.A |   1,000 |      $3,544.18 | 09/16/2001

### Trust 2: Wadsworth International ###
Wadsworth International is the trust that manages all of the family's assets outside of the US. For tax purposes, they have not repatriated the money, so it can only be spent outside of the US. The assets in this account are: 

You see where I'm going. Personas don't have to be limited to humans and/or clients, as well. They could be companies, external agents like regulatory auditors, or even a pet (if you're running a vet, for example).

The promise of BDD is executable documentation. It's not hard to imaging taking these scenario files, combining them with the persona markdown, combining those with the persona SQL, and creating a fully cross-referenced site of the test cases, combined with the personas, combined with the test data generation. That's left as an exercise for the reader.

Summer of Seminars

Please join us for our June and July seminars in Kirkland, WA!

Introduction to Docker - 6/19

Heard about Docker, but not sure what it is? Interested in learning about how Docker can improve your development speed? How it can help you standardize and improve your environment management? Or how Docker can help you save money and get more bang for your buck with both on-premise environments and cloud-based services?

This hour-long presentation will walk you through Docker in clear, straight-forward language. We will walk you through how to approach Docker PoCs and evaluations, and how to integrate Docker into your existing environment.

Escape The Matrix - 6/26

In this presentation, we'll present a common industry organizational design pattern - the cross-fuctional matrix - and learn how it works, alternatives, and strategies for both mitigation and transformation.

Intro: Cucumber, PhantomJS, Selenium - 7/10

Cucumber is an popular platform for building test suites that are easy for business stakeholders to understand. In this session, we'll introduce and compare traditional JUnit-style tests with Cucumber-style BDD testing. We'll show how to add in Selenium-based testing to automate UI/browser testing, and then we'll show how to use PhantomJS to run those Selenium tests quickly. We'll also talk about how this integrates into a continuous integration environment, and walk through an example of how all of this is hooked together on GitHub.

Introduction To Kanban 7/31

Are you trying to introduce change into your organization, and feel like you’ve hit a brick wall? Do you want to move forward with Lean initiatives, but are not sure how to apply them “in the trenches”? Have you adopted Agile principles and practice Scrum, but find it limiting when dealing with multiple teams and/or cross-functional organizations?

Kanban is an increasingly popular system for introducing incremental, evolutionary process into an organization. Based on Lean principles, it offers a way to move beyond basic Scrum and improve process in a consistent, manageable fashion. Dev9 has helped clients transition to Kanban, and we would like to share our engagement experiences.

Please join us for a discussion of Kanban and how it supports more effective technology management!

6/19: Introduction to Docker

Introduction to Docker

Fast, Standardized, Managed Environments

Heard about Docker, but not sure what it is? Interested in learning about how Docker can improve your development speed? How it can help you standardize and improve your environment management? Or how Docker can help you save money and get more bang for your buck with both on-premise environments and cloud-based services?

This hour-long presentation will walk you through Docker in clear, straight-forward language. We will walk you through how to approach Docker PoCs and evaluations, and how to integrate Docker into your existing environment.

Performance 101: Causes of Bad Performance

In the previous articles, we talked about some language and concepts, and then we got into tools and some more math. This has allowed us to identify places we should spend our time.


The first question we ask ourselves when we're tasked with performance enhancements is why? There are a lot of factors to consider, however, there are some basic rules you can start with.

The first breakdown we have is identifying if the problem is a contention or algorithm performance issue. This maps almost directly to our throughput vs. latency talks from the first article. These are the vast majority of performance issues you might encounter. Contention is what prevents us from getting the throughput that we want.

Algorithm performance affects latency. Everything works as expected, with little contention, but it's still not fast enough. These problems, while they're more fun to fix, can also mean huge changes. Making a sorting algorithm or a queue implementation or a face detection algorithm faster is an example of algorithmic performance.

NOTE: While this article is mostly about identifying performance issues in your application, do not overlook the importance of identifying and fixing performance issues in software that your app depends on. Database servers are a common source of issues, for example. You should be running the contention checks on these services if your tests slowness in that area

Algorithm Performance

Since we are going to spend the majority of our time talking about contention, let's spend a few minutes talking about algorithm performance. I consider an algorithm performance problem one where increasing the speed of the computer is the only way to improve performance. All contentions are minimized, but the code is running into fundamental limits from the hardware.


What we are talking about is the basis for Big-O notation. When you see O(n) or O(1) or O(n^2), these are Big-O examples. It helps us figure out the behavior of the algorithm with no restrictions. A merge sort (O(n log n)) is faster than a bubble sort (O(n*n)) because it needs to consider fewer things.

Data Structures

This type of performance issue can also arise when you use improper data structures. This is why it's important for programmers to at least be aware of the differences between arrays, linked lists, trees, and maps.


The last bit of note here is one we have all probably done: caching. If you've ever used ehcache or terracotta or memcached or even Hibernate, you've taken advantage of caching. The ability to skip a lengthy computation if the value doesn't change too frequently can mean the difference between 2 and 100 servers to handle the load you want. This can often be used for a quick performance gain if it's your first pass through the application.


A computer has a finite amount of resources. Contention is when one of these resources is utilized to its maximum capacity, and there is a queue of work waiting to be done. That resource simply can't handle any more work. Common sources of contention are discussed below, as well as some ways to mitigate the effects.

Disk Contention

Disk contention is when we spend too much time reading and writing data on disk. Because a spinning disk needs to get to the point on disk where you dsata lives, it takes some amount of time to get data back. If you have a lot of read and write tasks, your request may queue up behind others who haven't been served yet. This will result in long i/o wait times.

To investigate this issue on *nix-like systems, use the tool iostat. An example of a healthy disk setup:

Healthy Setup

You can see all the different devices in this example (thanks to Roger for putting it on the internet). The interesting things are the avgqu-sz and await. avgqu-sz is the average size of the request queue. In a mostly-idle system, this will be somewhere around zero, which means all requests are served quickly. In a system with disk contention, this number will grow rapidly. Await is the average time (in milliseconds) that a request took to process -- including queue time and serving time. Let's look at an unhealthy iostat:

Unhealthy iostat

There are a lot more devices on this machine, but you can see certain devices have a large queue size, and you can see the await times. If you want to serve a webpage in 100ms, but your disk is taking 105ms to service a request, you're going to have a bad time.

Blocking vs. Non-Blocking IO

You've surely heard about node.js by now. It's famous for its non-blocking IO. Whenever your application does something that needs to talk to disk (or something that would cause a wait), it yields to another task, and lets that original task finish later when the data is available.

Java also has some of this. There's a package for blocking IO, and it's probably what most of us use. There's also the java.nio package for non-blocking IO. If you find that waiting for disk becomes an issue, see if you can use non-blocking IO calls to speed up your server's ability to handle more.

Reducing Contention

To reduce disk contention, there are four common strategies. First, you can buy your way out. Solid-state drives (SSD) are significantly faster than spinning disks for random seeks. If your access pattern is a lot of small reads and writes, this will get you very significant benefits in performance. If, instead, your performance problem is one of reading and writing very large chunks of data, an investment in an enterprise storage system may be warranted. A RAID setup combines multiple disks into one, providing (usually) both fault tolerance and increased throughput, since multiple drives contribute to the end result.

The second common strategy is to simply reduce the amount of data that is on the disk. If you can get by with smaller files, that may increase speeds. Compression can be used on large files, as expanding it in-memory can be faster than reading uncompressed from the disk. A different serialization format can result in significant disk savings (JSON, for example, is quite verbose compared to CSV).

The third common strategy is to do batch reads/writes. This is what your hard drive controller does, which is why it's so dangerous to just unplug your computer. There is a disk cache that waits for some amount of data, then writes it all to disk at once. This is how some high-performance NoSQL engines work. They keep as much working data in memory as possible, and flush to disk periodically.

The fourth common strategy is to do more caching. Your operating system likely does some of this for you, by caching frequently-used files in memory. Your application can do the same. If the data on disk changes infrequently, you might want to read it to memory when your app starts up. If it's very large, and you do a lot of searching, see if you can index the file, or sort the file, so you can use faster algorithms like a binary search to get to your data.

This problem can be magnified if you use disk stores backed by networks. NFS, NAS, Samba, SAN -- these are all disks backed by network. While they may offer unparalleled data security and storage capacity and data mobility, you incur some overhead since it needs to communicate over a network. That leads us to our next step...

Network Contention

Networks have a lot of the same issues we have been discussing (latency, throughput, queueing). There's also the issue of network card capacity and network connection capacity. Most servers these days should have a gigabit ethernet card, and high-end servers should be using 10gb ethernet. But if your switches/routers are only capable of 10mbit, you will have a problem.

To look for potential network issues, there are two tools that are useful. First, there's the venerable netstat. This tool is useful to inspect network connections on the server. This can help you diagnose if you need additional threads to handle connections, if you're leaking connections, or if your system is being overwhelmed by connections. Second, there's a little utility called iftop. It periodically tracks the throughput of all network devices. It can drill down to a single connection, aggregate all connections, and track peaks and means. If you have a 100mbit network card and see ~10MB/sec in iftop, there's a good chance you're maxing out your network. Here's a little screenshot of it running with -t (to just print text to the console instead of an interactive app):


Solving network issues can be tricky business. Lucky for us, it's also probably not the source of problems. I have seen it be the source of problems one or two times. In those cases, if you took a thread dump of the process under load, you would see multiple threads blocking on a process that is waiting in the function socketRead0 or socketWrite0 -- native code that actually does the socket communication. Sadly, thread dumps are the most reliable way I've found to differentiate between network issues and other forms of contention.

CPU Contention

CPU contention is fun, in a way. We all know the command 'top' to display system load and running processes. In the modern world, with lots of threads and processes, it can be helpful to get a bit more detailed in our analysis. The tool htop breaks down each core's load, and provides a lot more than the default top:


Notice how all 4 cores are showing a high level of usage in this screenshot. I highly recommend this tool to verify that your CPU is overloaded.

While this is one of the easiest metrics to inspect, it can be very difficult to fix. The system just has too much to compute to do much more. This is where algorithmic fixes and better data structures come into play. If you notice the system bogging down but the CPUs are not maxed, you have some other contention slowing it down.

System Load

The load average from the above screen shot shows the 1-, 5-, and 15-minute averages of load. The load average is an exponentially dampened snapshot of running and runnable processes correlated with wait queue length. With multi-core machines, it gets even trickier. If it was truly just CPU, a 4-core machine with a load average of 1.00 is ambiguous. Is that 1 core fully maxed (and thus ripe for paralellization), or all 4 cores running at 25%? Maybe 2 cores at 50%? With multiple cores, a load average of 4 doesn't necessarily mean the system is under any stress. This is where tools like htop above help diagnose the issue

Memory Contention

Memory contention is when there is more memory being used than available on your system. Thanks to swap partitions, this shouldn't crash a machine. However, it's likely to destroy your performance. The more tuned your app is, the more detrimental swapping will be. Memory contention can also come when you run into out-of-memory (OOM) problems, or issues with garbage collection in managed apps.

Swap-based issues are easy to spot, as top or htop will tell you the amount of swap they're using. For a production system, you ideally want no swap used. Putting 128GB or more on one machine is perfectly doable these days.

Out-of-memory usually surfaces as a process that dies unexpectedly with no messages. The only way to fix this is to consume fewer resources. This, again, is where better data structures or more compact object representations may help. You may also have memory leaks.

Garbage Collection

Garbage collection tuning, especially in Java, is almost a job unto itself. There are a lot of tunable parameters. There is the permgen vs. the heap. There's the issue of heap resizing vs. fixed-size heap. When you profile your Java app, you really want to see the classic saw-tooth pattern:


This is a generally healthy system. The garbage collector kicks in and returns the heap to about the same size. A more unstable or growing-memory system looks like this:


Notice how the "free heap" blue line climbs, then eventually drops, despite garbage collection happening on the green line. When the free heap is near zero, Java will spend a lot of its time trying to free up the heap, including multiple stop-the-world pauses. These can range from a second or so to multiple minutes, depending on heap size and object counts. If you let it run like this long enough, it will probably become unresponsive and eventually crash with an out-of-memory error.

Tuning the GC is beyond the scope of this article, but it can dramatically improve performance.

Memory Leaks

The last thing to look out for is memory leaks. Technically it's impossible to do this in Java if you're not using unsafe libraries, but in practice it's a problem. The biggest issue is dangling references to objects that you no longer need. It keeps these objects around in perpetuity, and that could eventually kill your heap. Using tools described in the previous article (visualvm, jprofiler, yourkit), you can inspect where these objects are created, which ones take the most space, and what types of objects they are. This can be very helpful in tracking down excessive memory usage.

There is a fascinating issue in Java that has cropped up occasionally. If you have a very large string (say, a JSON or XML document, or a large text file you've put into a string), then take a substring of it, that substring is just a windowed view of the larger text string. This is good when your strings are small, as it prevents a lot of reallocation. However, when the source is very large, your substring holds a reference to that large document, meaning your memory usage is far larger than normal. This "leak" was fixed in OpenJDK 7u6. If you're still on JDK 5 or 6, you're probably being affected by this.

Lock Contention

This is where things get really tricky. I've also found that it's the source of a lot of issues, so it's good to get well versed in this kind of contention. Because multiple threads accessing the same resource (variable, array, database connection, etc) can stomp on each other, there needs to be a way to control access to these sensitive bits. In Java, we often put synchronized on the method definition, or put a critical block inside a synchronized block. Behind the scenes, it creates a lock so that only one thread can execute here at a time.

When there are a lot of processes vying for the same lock, you are slowing them all down. If your locks are implemented as spin locks, it may exhibit 100% cpu usage while it waits. If you take a stack trace, you will see "Waiting on 0xXXXXXXX" for threads that are waiting for a lock. A useful tool for some users is TDA, and this is how it presents there:

Thread Dump

Not all locks are deadlocks. Deadlocks are two threads waiting for locks that the other holds, with no way to make progress. Most profilers offer tools to automatically detect deadlocks, and will make your life significantly easier.

Lock contention is so expensive that multiple languages/frameworks/patterns are designed to avoid it. Functional programming languages often avoid this issue because they do little-to-no variable mutation. Immutable data structures simplify your life significantly. Because they can't change, it's safe for multiple threads to access the data. Lock-free queues are popular in some circles, but they can be nasty to code up correctly if you're not extremely well-versed in this specialty.

Mechanical Empathy

If you're going the ultra-high-performance route, there's a concept you should be aware of called mechanical empathy. This describes a way of organizing your parallelism to minimize the burden on the CPU, especially context-swaps. When you're trying to design sub-millisecond responses in a managed language, it can be difficult to achieve using traditional methods.

Mechanical empathy was invented and popularized by the LMAX Disruptor. From the PDF of the whitepaper, this graphic comes to explain the cost of locks:

Lock Cost

You see that as contention (and thus arbitration) increases, your throughput gets tanked. LMAX Disruptor is an attempt to design a system to minimize locking and minimize expensive context switches.

This is not a simple implementation, and it's not a drop-in replacement for, say, ConcurrentHashMap. Read the link above to get a lot more information and see if it's the right approach for you.


This wraps up our tour of the most common cases of poor performance, and some things to look out for. Becoming proficient at analyzing and tuning the JVM as well as analyzing and tuning your own applications, you will have a much deeper understanding of your own code, as well as a much deeper understanding of how the JVM works, which might make for better code. Go forth and profile!

A Few Quick Notes on Heartbleed

Heartbleed is an major security problem found in OpenSSL, a very popular encryption package.

An excellent (code-level) technical description can be found at the Register.

Unfortunately, there are a LOT of embedded systems out there with no easy way to patch.

Action items for everyone:

  • Download and review the OWASP Top Ten
  • Make sure you are using static code analysis tools to catch common errors. A reporting “kitchen sink” Maven project posted on our GitHub which includes a lot of reports, such as test coverage, static code analysis, code complexity, and much more.
  • Be sure you understand how important test suites, code coverage tools, and deployment automation are for both preventing these issues and being able to quickly deploy when there are updates. Including being able to quickly test that the applications still work when patches come out.

The guy who checked in the OpenSSL bug is now famous... lucky him. >_<

Tools I Use (Mac OS X Edition)

I'm a bit of an oddity - I use and basically like Mac OS X, Windows, AND Linux.

People sometimes look at me funny - it's hard to be "multi-lingual." My experience has been that while all three have their quirks, it's actually easier to understand all of them in reference to each other. I'm told that after you learn a few languages, learning more is easier because you start to understand how language works at a more fundamental level. Once you start to understand how an operating system is built, switching to a new one isn't that bad.

Once you get over the basics (network config, keyboard commands, file management, system layout, etc.) the biggest challenge is building out a decent collection of software to support your day-to-day work. Some software (e.g. IntelliJ IDEA, Eclipse, NetBeans) is available for multiple platforms - aside from learning slightly different keystrokes, no big deal.

We've had a number of people coming to the Mac recently from Windows, and so without further ado here are some of my favorite apps from the App Store:

The two main apps not available on the App Store I use besides the dev environments above are XMind and (of course) Office.

What are some of your favorite apps? Any tricks for making it easier to learn a new OS?