Software Teardowns: Console.WriteLine (Part 1: Windows)

I love teardowns, and I spend a lot of time looking at the articles that tear down different consumer products to show how they’re made. Software teardowns are harder though. It’s usually difficult to figure out a discrete piece to look at and tear it down without a whole lot of problems. Or at least, that’s what I’ve always thought.

Today, I’m going to take a look at the Console.WriteLine method in .NET Core; and attempt to ‘tear it down’. I’ll take it as far as I can, and we’ll see where I get. I haven’t ‘pre-planned’ this (though I have trawled through the .NET Core source code before on an unrelated issue, and am reasonably sure this won’t suck). I’ll attempt to stick to just the act of writing a character to the console (and printing a new line); but I may see other things I want to talk about along the way. Ado aside, here we go.

The source code for the .NET Core framework (called corefx by whoever names these things) can be found under the .NET Foundation’s github page, here. The .NET Core Framework (I’ll just call it corefx or The Framework from here on out) is meant to be a managed library of pre-built classes and features you can use as a programmer. You’ll hear “Standard Library” thrown about in various languages; corefx is .NET Core’s Standard Library. You could create your own if you wanted to (the Mono team did); but generally unless there are licensing concerns, don’t re-invent the wheel. A note about licensing, corefx is MIT licensed; so there shouldn’t be any licensing issues. (You can always find licensing information in each source code file, as well as a ‘repo-level’ LICENSE.MD, LICENSE, or LICENSE.TXT file or some such. CoreFx’s license is here.

For this post I’ll be referring to this revision of the framework. It’s currently ‘master’ as well; but master is nebelous as to whatever’s checked in; and I want to be able to point to specific pieces that may change in the future.

The first thing of note is that The Framework makes use of several third-party libraries and source code(s) (todo: figure out the plural of source code: “source codes”, “sources code” or “source code”), and they spell out a notice here as to what they use and where it’s from. Several interesting tidbits, including “Bit Twiddling Hacks”, “decode_fuzzer.c” and Brotli. I have no idea what Brotli is; but I’m curious to know.

That aside, the central question I have is:

Given this simple program; what is the resulting look of the code that prints characters to the console that gets used on Windows? On Debian-Based Linux Machines? (I’m not as interested in the compiled IL right now).

using System;
public class Program {
    public static void Main(string[] args) {
      Console.WriteLine("Hello World!");
    }
}

Because I am importing System, I would expect the Console class to be right underneath System; and lo and behold it is.

The source code structure surrounding it is interesting.

If I click on src, underneath corefx, I see a whole bunch of namespaces that I typically use in applications:

well these look familiar…

The one at the top is interesting; it’s called Common. Even Microsoft can’t get away from a dumper folder, eh?

It looks like at least part of the Common is a sync-ing point between projects, at least it says that on the tin.

Upon further inspection, due to the myriad of internal classes (I’ve spot-checked and all are marked with the internal identifier), I’d classify this code as necessary to build/develop for the .NET Framework; but not necessary for consumers of the .NET Framework.

That detour finished; I click on System.Console and open it up to inspect what’s going on. There shouldn’t be that much here, right?

The first thing I notice is that System.Console has its own .sln file; so presumably if we ever need to make changes to System.Console, you don’t have to load the entire .NET Framework source. This is probably a recurring theme; but interesting to note.

This ends up being a common theme. .sln, .props, ref, src, and tests… I wonder if it’s code-gen’d?

The second thing is there is a ref folder, and it contains a partial Console class; with all of the property and method signatures needed for this class. It has no implementation, however. I’m not really sure why it’s here; but to guess (way out of my element, mind you); would seem it could be there so someone could check API Compatibility without needing the whole framework source. As I said, I have no idea; and I’ll have to google more to figure out why it exists. Interestingly enough there’s a short-link at the top of this file that points to the API Design guidelines for third-parties to request their library/class be made as part of the System.* namespace. They even include an example of a recent process to add classes to the namespace. It is worth a read.

In the ref folder, besides the partial definition of the System.Console class; there are also Configuration.props files and a System.Console.csproj file.

I really have no idea what “ref” is for but it looks important.

It still uses the non-SDK tooling (which isn’t surprising — but it makes you wonder — if Microsoft can’t use their own SDK tooling for the .NET Core Framework Library; what’s the hope for the rest of us?). (Editor’s note, I wrote this at the beginning of 2018; 1 year later, it still uses the non-SDK tooling).

I assume the .props file is to give some hints as to how to build this; there are two interesting build properties that I haven’t seen elsewhere (yet):

    <IsNETCoreApp>true</IsNETCoreApp>
    <IsUAP>true</IsUAP>

IsNETCoreApp is used here, and it (unsurprisingly) is used during building the Framework, and is used to reduce the build to only projects that are a part of .NET Core.

IsUAP is an acronym I hadn’t heard before; and a quick Googling suggests it’s the same as UWP (Universal Windows Program). Not sure if this is a marketing change, or if UAP actually means something different than UWP. I thought UWP was The Right Acronym For This Thing (TRAFTT); and it appears that UAP is an earlier naming. Considering the build tooling isn’t using the latest; they probably haven’t gotten around to the name change yet (and who would want to?)

Now that Github has stopped rate limiting my searches, I can go back to explaining what is going on here. I should probably switch over to grep; but I’m trying to keep this lightweight. You know, besides all the commentary.

IsUAP is slightly more interesting; as it also has runtime considerations. It’s used during building to determine where to put the bin folder but it’s also used by test code to ‘do things differently’ depending on if it’s UAP or not. It looks like UAP uses a WinRTWebSocket, and non-UAP uses WinHttpWebSockets. I’m literally monkey-typing what I see here, and there are lots more questions than answers, but there it is. There are several places where UAP differs from non-UAP; I’m just highlighting one.

The tests for System.Console are interesting. Anything that tests the Console is by definition an integrated test; so I’m cracking these to see how they delineate Unit Tests from Integration Tests.

Interestingly (I know, I know, I use that word too much), it appears that in order to test the System.Console class; The Framework authors wrote a helper class to intercept what is sent to the console and look at the MemoryStream, instead of it actually getting sent to the Console.

It also appears there’s a ManualTests class to actually have a user test the console.

I have lots of questions that I’d probably get answered by running the tests themselves (but that’s not why I’m here today).

Now to the meat of what I wanted to talk about; the Console class itself.

It appears the Console has its class, and then there are UnixPal and WindowsPal classes that actually act as implementations for particular platforms (Windows, Unix). I’m guessing “PAL” stands for Platform Abstraction Layer; but again, that’s a guess. A quick Google Search reveals even more goodies, a Github project I never knew existed!

The System.Console.csproj file contains build switches to determine which ConsolePal class to bring in. The ConsolePal.<platform>.cs class is an internal class; and purely a drop-in replacement for implementations on different platforms.

The class sends hints to the compiler not to inline the methods; this appears to be done for ease-of-debugging reasons:

        // Give a hint to the code generator to not inline the common console methods. The console methods are
        // not performance critical. It is unnecessary code bloat to have them inlined.
        //
        // Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
        // the inlined console writelines from them.
        //

The particular overload of WriteLine I’m concerned with is this one:

public static void WriteLine(String value)
{
  Out.WriteLine(value);
}

Out in this context refers to a public member that is of type TextWriter.

public static TextWriter Out => EnsureInitialized(ref s_out, () => CreateOutputWriter(OpenStandardOutput()));

s_out refers to a private TextWriter member, and that is passed to EnsureInitialized along with a Func<T>, and EnsureInitalized has the following definition:

internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class =>
            LazyInitializer.EnsureInitialized(ref field, ref InternalSyncObject, initializer);

Since it’s turtles all the way down, the EnsureInitialized in turn calls a LazyInitializer class (which probably follows the Lazy Initialization (aka, Lazy Loading) pattern.

This LazyInitializer class is written to be Thread Safe, and overall if you’re interested in “How would I lazily initialize members in a high-performance situation”, the code for this class is worth a look. Upon further inspection (My eyes glazed over the public modifier); it looks like you can use this in your code (so that’s cool — and I’ll have to try this).

The next part of the EnsureInitialized method call for Out is the CreateOutputWriter(OpenStandardOutput()) method. Briefly, it does the following:

public static Stream OpenStandardOutput()
{
    return ConsolePal.OpenStandardOutput();
}

OpenStandardOutput() is an abstraction over the system specific method of opening Standard Output,

And CreateOutputWriter does the following:

private static TextWriter CreateOutputWriter(Stream outputStream)
{
    return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
        StreamWriter.Null :
        new StreamWriter(
            stream: outputStream,
            encoding: new ConsoleEncoding(OutputEncoding), // This ensures no prefix is written to the stream.
            bufferSize: DefaultConsoleBufferSize,
            leaveOpen: true) { AutoFlush = true });
}

It’s important to note that the outputStream that is a parameter is the previous ConsolePal.OpenStandardOutput() method; so we’ll examine that further when we break off into the Windows vs. Unix implementations.
At this point, I’m going to go down two paths; what Console.WriteLine does on Windows in this blog post, and Unix in another blog post.

Windows

The first step as we saw above was to OpenStandardOutput(), and for Windows that method can be found here:

public static Stream OpenStandardOutput()
{
    return GetStandardFile(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE, FileAccess.Write);
}

It returns a Stream; and makes a call to GetStandardFile with two parameters.

Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE

From my C days (I’m still a junior C developer, mind you), I can guess that STD_OUTPUT_HANDLE is a constant, and navigating to Interop.Kernel32.HandleTypes confirms it:

internal partial class Interop
{
    internal partial class Kernel32
    {
        internal partial class HandleTypes
        {
            internal const int STD_INPUT_HANDLE = -10;
            internal const int STD_OUTPUT_HANDLE = -11;
            internal const int STD_ERROR_HANDLE = -12;
        }
    }
}

The internal tells me this is for the Framework itself (not us), and it being a partial class tells me there will be another section of this class elsewhere. I can’t seem to find it (again, I’m basing it off of source code available via github, and not having it built locally), so I have unanswered questions as to what is this for and why it is partial.

STD_OUTPUT_HANDLE is a constant that is set to -11, so that value has meaning for GetStandardFile (likely it means that Win32 has hardcoded outputing to StdOut as -11).

FileAccess.Write is an Enum Flag that is a clean way to tell the underlying Win32 libraries that we want to ‘write’ to the Console Output “stream”.

As an archeological note, it appears that the System.IO.FileSystem.Primitives project that FileAccess sits in uses an older version of .NET Core, as evidenced by its use of project.json.

The method declaration for GetStandardFile is as follows:

private static Stream GetStandardFile(int handleType, FileAccess access)
{
    IntPtr handle = Interop.Kernel32.GetStdHandle(handleType);
    // If someone launches a managed process via CreateProcess, stdout,
    // stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
    // Additionally they might use 0 as an invalid handle.  We also need to
    // ensure that if the handle is meant to be writable it actually is.
    if (handle == IntPtr.Zero || handle == s_InvalidHandleValue ||
        (access != FileAccess.Read && !ConsoleHandleIsWritable(handle)))
    {
        return Stream.Null;
    }
    return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType));
}

Let’s break this down.

IntPtr is an integer sized pointer struct; and it’s used to get a pointer to the handle we’ll be writing to.

Whether it’s a 32-bit or 64-bit size is dependent on a compiler flag:

#if BIT64
using nint = System.Int64;
#else
using nint = System.Int32;
#endif

I have multiple questions here (having never seen the internals of this struct before), and I have to say most of this code is deep in the weeds code. To see which overload of this struct initializer is used, I’ll have to see what InteropKernel32.GetStdHandle(int) does:

using System;
using System.Runtime.InteropServices;
internal partial class Interop
{
    internal partial class Kernel32
    {
        [DllImport(Libraries.Kernel32, SetLastError = true)]
        internal static extern IntPtr GetStdHandle(int nStdHandle);  // param is NOT a handle, but it returns one!
    }
}

Ok. At this point we are making a call into the Win32 libraries; specifically the Libraries.Kernel32 library. I’m going to check to see if I can dig into the internals of the Libraries.Kernel32 class, but likely will not be able to (darn you, closed source). Yea, a quick Google Search indicates this is the end of the line for determining how it gets a handle. On the Unix side we’ll be able to dig deeper than this, but for Windows we’ll have to stop here on getting the handle. If you ever want to know about the internals of Windows, make sure you read The Old New Thing, it’s Raymond Chen’s blog; and is (with apologies to a certain comedian, quite amazing).

Once it gets the handle, it checks to make sure the handle is valid to write to:

// If someone launches a managed process via CreateProcess, stdout,
// stderr, & stdin could independently be set to INVALID_HANDLE_VALUE.
// Additionally they might use 0 as an invalid handle.  We also need to
// ensure that if the handle is meant to be writable it actually is.

The comment above is great; it doesn’t just restate what the code does; it tells why the code does what it does. If you’re going to write comments in code, be like this commenter.
And the code itself:

if (handle == IntPtr.Zero || handle == s_InvalidHandleValue ||
    (access != FileAccess.Read && !ConsoleHandleIsWritable(handle)))
{
    return Stream.Null;
}

IntPtr.Zero is likely a Windows-wide ‘null’ or sentinel value for a pointer.

s_InvalidHandleValue is by default:

private static IntPtr s_InvalidHandleValue = new IntPtr(-1);

and access cannot be ‘read’ only (read and write would be OK), and the ConsoleHandleIsWritable must be set to false.

This code gave me a headache for a minute because I realized this entire if statement is meant to be a guard clause; if any of these conditions exist, we can’t write and should therefore return Stream.Null. I can’t find System.IO.Stream (though as I understand it it is an abstract class); though it looks like CoreFX has moved it to the System.Runtime.Extensions namespace, and the cleanest definition I can find for Stream.Null is that it appears each child class of Stream (some or all) redefine it using the new operator:

public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true);

Before we pass the guard-clause, there’s one remaining method in the if statement: ConsoleHandleIsWriteable(IntPtr).

I’m pasting it below (with its comments) in its entirety; and the comments are A++ (would vote A+ again):

// Checks whether stdout or stderr are writable.  Do NOT pass
// stdin here! The console handles are set to values like 3, 7,
// and 11 OR if you've been created via CreateProcess, possibly -1
// or 0.  -1 is definitely invalid, while 0 is probably invalid.
// Also note each handle can independently be invalid or good.
// For Windows apps, the console handles are set to values like 3, 7,
// and 11 but are invalid handles - you may not write to them.  However,
// you can still spawn a Windows app via CreateProcess and read stdout
// and stderr. So, we always need to check each handle independently for validity
// by trying to write or read to it, unless it is -1.
private static unsafe bool ConsoleHandleIsWritable(IntPtr outErrHandle)
{
    // Windows apps may have non-null valid looking handle values for
    // stdin, stdout and stderr, but they may not be readable or
    // writable.  Verify this by calling WriteFile in the
    // appropriate modes. This must handle console-less Windows apps.
    int bytesWritten;
    byte junkByte = 0x41;
    int r = Interop.Kernel32.WriteFile(outErrHandle, &junkByte, 0, out bytesWritten, IntPtr.Zero);
    return r != 0; // In Win32 apps w/ no console, bResult should be 0 for failure.
}

And here’s the signature of Interop.Kernel32.WriteFile():

 internal partial class Kernel32
{
    [DllImport(Libraries.Kernel32, SetLastError = true)]
    internal static extern unsafe int WriteFile(
        IntPtr handle,
        byte* bytes,
        int numBytesToWrite,
        out int numBytesWritten,
        IntPtr mustBeZero);
}

It looks like this is to make a system check to see if this is a writable location by actually trying to do it, and what I can ascertain (again, without seeing the Kernel32.WriteFile source) is that it tries to write zero bytes to the supplied handle, and the exit code from trying to run this function should be non-zero. (Which is interesting because 0 is generally success).

And if the guard clause is passed; the interesting part for us is now:

return new WindowsConsoleStream(handle, access, GetUseFileAPIs(handleType));

line (here).

Before diving into that class, I first want to resolve what GetUseFileAPIs does, so I’ll find that, and it turns out to be a private method in this class:

private static bool GetUseFileAPIs(int handleType)
{
    switch (handleType)
    {
        case Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE:
            return Console.InputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsInputRedirected;
        case Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE:
            return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected;
        case Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE:
            return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsErrorRedirected;
        default:
            // This can never happen.
            Debug.Assert(false, "Unexpected handleType value (" + handleType + ")");
            return true;
    }
}

while I applaud their confidence at the default state; I’ll keep the commentary on just the part of the case/switch we care about:

case Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE:
    return Console.OutputEncoding.CodePage != Encoding.Unicode.CodePage || Console.IsOutputRedirected;

And now we’re into OutputEncoding, and particularly I don’t quite understand the ‘why’ behind this; but they want to make sure the OutputEncoding is unicode, or that the output is being redirected. If either of those things is true; then the intent is to use File APIs (and not the console?). I have questions behind this; but from what I can gather the Console API assumes Unicode and redirecting the output would mean it’s going to a file (typically).

WindowsConsoleStream

I’m relatively sure at this point we’re nearing the “We’re about to print to the console” stage; (it’s in the name, right?). The WindowsConsoleStream is a private class that provides the ability to stream to the WindowsConsole.

The constructor for this class follows:

internal WindowsConsoleStream(IntPtr handle, FileAccess access, bool useFileAPIs) : base(access)
{
    Debug.Assert(handle != IntPtr.Zero && handle != s_InvalidHandleValue, "ConsoleStream expects a valid handle!");
    _handle = handle;
    _isPipe = Interop.Kernel32.GetFileType(handle) == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE;
    _useFileAPIs = useFileAPIs;
}

The Debug.Assert is a nice touch (I’ll go into it more below); and the only new thing we haven’t seen before is the GetFileType for the handle to determine if we’re trying to pipe the output.

A quick Github search brings a set of constants (set to 0x0003):

and since it’s derived from ConsoleStream, here’s the constructor for that class as well:

internal ConsoleStream(FileAccess access)
{
    Debug.Assert(access == FileAccess.Read || access == FileAccess.Write);
    _canRead = ((access & FileAccess.Read) == FileAccess.Read);
    _canWrite = ((access & FileAccess.Write) == FileAccess.Write);
}

Nothing new here; it’s just setting an internal variable to whether we can write to the Console. Debug.Assert is rather interesting, and bears its own blog post; but in short: Debug.Assert is a throwback to C programming where invariants (things that if they happen mean something is fundamentally broken) were checked using a macro (because C), and that macro generally looked like ASSERT(ThingThatShouldNeverBeFalse) (the uppercase ASSERT was to let other programmers know it was a pre-processor macro). That practice carries on, except now, Debug.Assert is a real thing, with an implementation in the .NET Core Runtime.

There are several interesting parts here (and I refuse to let myself be sucked into them; but I’ll mention them nonetheless):

[System.Diagnostics.Conditional("DEBUG")]
public static void Assert(bool condition, string message, string detailMessage)
{
    if (!condition)
    {
        string stackTrace;
        try
        {
            stackTrace = Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
        }
        catch
        {
            stackTrace = "";
        }
        WriteLine(FormatAssert(stackTrace, message, detailMessage));
        s_ShowAssertDialog(stackTrace, message, detailMessage);
    }
}

First is that it appears (without checking into consumers of the ConditionalAttribute attribute) that this code will only be compiled in to the Runtime on a “DEBUG” build (if the DEBUG switch is activated on the build?)

Second is that it looks (again, I’m guessing) that it produces a StackTrace up to the point where the DebugAssert was called, and then there is likely a platform specific s_ShowAssertDialog that is called to let the developer know something bombed.

Back to the fun. So it looks like once the WindowsConsoleStream class is instantiated, there are three things you can do; read, write, and flush.

We’ll focus on the Write part (though Flush is probably useful too).

public override void Write(byte[] buffer, int offset, int count)
{
    ValidateWrite(buffer, offset, count);
    int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs);
    if (Interop.Errors.ERROR_SUCCESS != errCode)
        throw Win32Marshal.GetExceptionForWin32Error(errCode);
}

It calls ValidateWrite which ensures the values are correct:

protected void ValidateWrite(byte[] buffer, int offset, int count)
{
    if (buffer == null)
        throw new ArgumentNullException(nameof(buffer));
    if (offset < 0 || count < 0)
        throw new ArgumentOutOfRangeException(offset < 0 ? nameof(offset) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
    if (buffer.Length - offset < count)
        throw new ArgumentException(SR.Argument_InvalidOffLen);
    if (!_canWrite) throw Error.GetWriteNotSupported();
}

and then it calls a private internal method called WriteFileNative that uses that _useFileAPIsboolean to determine which APIs need to be used (Screen or writing to a file)

WriteFileNative gets us to the guts of what happens. Let’s take this a section at a time.

private static unsafe int WriteFileNative(IntPtr hFile, byte[] bytes, int offset, int count, bool useFileAPIs)
{
    Debug.Assert(offset >= 0, "offset >= 0");
    Debug.Assert(count >= 0, "count >= 0");
    Debug.Assert(bytes != null, "bytes != null");
    Debug.Assert(bytes.Length >= offset + count, "bytes.Length >= offset + count");

First, it’s an unsafe method (likely because it’s touching things outside the framework), and the Debug.Asserts rear their heads again.

// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0)
    return Interop.Errors.ERROR_SUCCESS;

Return ERROR_SUCCESS. That’s good, right? I don’t know what the fixed statement is; but I guess we’ll get to that in a minute.

bool writeSuccess;
fixed (byte* p = &bytes[0])
{
    if (useFileAPIs)
    {
        int numBytesWritten;
        writeSuccess = (0 != Interop.Kernel32.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero));
        // In some cases we have seen numBytesWritten returned that is twice count;
        // so we aren't asserting the value of it. See corefx #24508
    }

Ok, that was quick. A google search tells me the C# keyword fixedis only used in unsafecode to tell the runtime the position of the memory should not be moved. The fixed keyword allows us to do pointer arithmetic in C# without the runtime mettling in our affairs.

This block of code also points out there’s an interesting bug in the framework where the number of bytes written doubles? Or maybe it’s counting characters when it should be counting bytes? Who knows?

    else
    {
        // If the code page could be Unicode, we should use ReadConsole instead, e.g.
        // Note that WriteConsoleW has a max limit on num of chars to write (64K)
        // [https://docs.microsoft.com/en-us/windows/console/writeconsole]
        // However, we do not need to worry about that because the StreamWriter in Console has
        // a much shorter buffer size anyway.
        int charsWritten;
        writeSuccess = Interop.Kernel32.WriteConsole(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero);
        Debug.Assert(!writeSuccess || count / BytesPerWChar == charsWritten);
    }
}
if (writeSuccess)
    return Interop.Errors.ERROR_SUCCESS;
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is not an error, but EOF.)
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Interop.Errors.ERROR_NO_DATA || errorCode == Interop.Errors.ERROR_BROKEN_PIPE)
    return Interop.Errors.ERROR_SUCCESS;
return errorCode;
}

If we aren’t using the FileAPIs, then call the Kernel32’s WriteConsole function with the appropriate handle, the current location of the pointer, how many characters we’re writing (count / BytesPerWChar ), a placeholder out variable that will contain what’s been written, and IntPtr.Zero. The final piece is to ensure that if the pipe is closed, then stop trying to write to the console.

Overall, this was a very interesting dive into the .NET Core framework. I’m a bit bummed that I couldn’t see more of what Windows does to actually print a character to the screen; but I feel like I’ll be able to do that in the next blog post, when we dive into how the .NET Core Framework prints to a Unix console.

Metaphors, Agile, and Us

I haven’t found a metaphor for programming that adequately describes its effect on business, maintenance, products, and developer sanity.

Manufacturing is probably the most used metaphor, and that tends to work for about as long as it takes to scream the words “mythical man month”, and with smarter people, that’s the end of that metaphor.

Then there’s gardening, or house building, or art, or carpentry, or some other activity that is superficially like programming. I use golf as a metaphor.  It’s an activity that requires following an exact procedure in a constantly new situation, it is largely mental, and there’s a physical limit to how long you can do it. It’s expensive, requires lots of practice, and to someone who has never done it before, it looks easy. It is also a personal activity, and there’s little use comparing two programmers, even under the exact same conditions.  People who aren’t doing it wonder what the trouble is, and people who do it can’t begin to explain how a leaf in the wrong spot can change everything.

Difficulty

Watching golf on TV is boring if you’ve never golfed, much like watching someone program. One aspect of golf that doesn’t translate to TV is just how hard they hit those golf balls. The ball itself makes sounds as it passes people. I’m not kidding. I can’t explain just how amazing watching a good golfer play is, and since you’re probably not likely to do it on your own, we will just have to take my word for it.

One area where golf really shines is that when someone is a good golfer, there are statistics to back them up.  Greens hit in regulation, scores, fairways hit, up and downs, all of it. We really don’t have the same sort of stats for programmers, do we. Even as I think about it there’s no immediate statistics that come to mind that would be universally applicable.  Bugs per 1kloc? Mean Time to feature completion? Revenue per 1kloc? Maintenance score? Story point average? Even if we could normalize these numbers across the industry there’s no authoritative source to say what’s valuable.

By and large golf is a solo activity. Others can (and do) help you decide on your strategy, but it’s up to you to execute it. Following someone else’s strategy blindly often results in a bogey, or worse. The effects of cargo-culting play out in real time as your ball goes sailing into the deep stuff. Bad decisions in golf can be cumulative, but after 4 and a half hours, you’ve made all the bad decisions.

All metaphors fail, and I suppose this is where the golf as programming metaphor fails. We should all be so lucky to see the effects of bad decisions after 4.5 hours in programming. Often the outcomes are small annoyances that add up, or a bad product direction that takes years to correct. There is no fast feedback in programming for bad technical decisions, and product decisions even less so. Everyone knows this, and everyone reacts to this reality differently. Project managers try risk registers, CTOs micromanagement, Architects enforce coding standards that have nothing to do with the problem at hand. Each party tries to control what it has dominion over. At least in golf, once the ball is in the air there is nothing you can do to retain control over your bad decision.

Course Management

In golf, there’s a phrase that is used to manage this phenomena, “course management”. At its heart, the strategy is to play to your strength and to the numbers. If you’re driving a 450 Yard par 5, you may as well hit 3 7-irons and make it on the green in 3. The 7-iron is one of the easier irons to hit, and your rational brain knows you aren’t making it in two anyway. It’s a lot safer to hit 150-150-150 than it is to try to drive 225-180-45. Most golfers can’t reliably hit woods and low irons (Golf clubs go from low numbers which can hit further to high numbers which can’t hit as far), and the flight of the ball is harder to control. Another side-effect of using the 7-iron is that if you need to readjust for your second and third shots, it’s easier to do so.

This is a well known strategy, carries little risk, and usually isn’t followed. Reasons vary, but distilled it comes back to ego, pride, and a foolish sense that this time it will be different. I know the strategy and even when nothing is at stake I have a hard time following it. I compare my skills to those next to me and so I try to play the same way they do, even though I’ve broken 100 a grand total of 1 time (I think. That’s 28 over par, in case you were wondering, or averaging 1.5 strokes over par per hole).  I am over-confident in my abilities, all evidence to the contrary. I see myself through their eyes; and want to impress them with my ability, and so I pull the driver out of the bag and use it, even though my hit rate with the Driver is 15% (I’m shockingly bad with a Driver, to the point that I now typically “drive” with a 3-hybrid). Going for the big hit doesn’t work if you’ve not successfully executed big hits in the past on a regular basis.  

Golf has the privilege of being a self-contained activity that’s at the mercy of external forces. It doesn’t matter how well you execute your shot if there’s a 40mph cross-wind, and yet the best you can do is adjust to changing factors and pray.  It’s like business in that regard. Technical decisions aren’t made for technical reasons alone. Choosing microservices may be due to a business requirement that teams are operating in parallel; or it may be because a monolith wasn’t “nextgen” enough. Or both.  Adding on business and product decisions to them and it’s impossible to be sure the decision is correct. At some point you have to swing the club to find out. Except the ball is your MVP, the wind is your business’s inertia, and the ball is heading into the woods.

Business decisions are critically important to the software we create, and yet I’d wager that for most developers you probably don’t realize what your most pressing business objective is right now. That’s ok, the code is hard enough. Strangely, the opposite is also true. Business people watch programmers in the same way tv viewers watch golf. It’s just typing, or it’s just a new menu, or it’s just restricting what a user can do after business hours. And just like golfers, we tell them it’s not that easy, but of course seeing is believing. The bad news is that it takes several people-months to show them how hard it is to fulfill their request. Software development has its own version of course management, called agile. Just like the green in three approach, it seeks to reduce risk by putting the effort and expected outcome in reach of everyone. Break the problem down into manageable and achievable chunks and work towards those. We may fail, but the cost of failure is smaller.  It allows software development teams of all skill levels to succeed, even teams that are in an unknown problem space. It really is the safest way to ensure failure chances are minimized and success is maximized.

Just like course management, agile only works if everyone commits to it. The caddy, the golfer, the people on TV, and the announcers. The management, programmers, the industry, and executives. The consulting industry has sold business that ‘agile’ means ‘going faster’, or ‘doing more with less’. Neither is true, and a great amount of ink has been spilled disproving these myths. Software developers, disillusioned with the promises of agile development  (notably the Scrum framework) combined with executives not truly buying in to the change, have decided to become “post-agile”. Executives revert to the tried-and-not-so-true method of asking for too much, Managers revert to command and control, and the industry apes what they see, because they think it’s successful.

Closing

The problems we encounter are at the seams of each discipline.  We understand programming is hard and requires exacting specifications, and we understand that business people need to see a return on their investment.  What we aren’t able to do is to align all of these forces cohesively. Post agile is great for developers.  It’s great for remote work.  It doesn’t solve the problem on measuring return on investment, because that’s not what it’s meant to do. It doesn’t solve the problem of establishing trust between business and development, because that’s not what it was meant to do. Agile development, for all its flaws, attempted to establish trust between developers and business, and to make development better for both the business and developers.  The promise of agile has succeeded when it’s been adopted by everyone in the organization; when everyone puts aside their egos and recognizes that past performance is an indicator of future performance; when businesses ask for bite-sized pieces of functionality instead of features that take people months to accomplish.  It has succeeded, and it can succeed.


What we’re missing is the metaphor that would convince business people and executives that software is hard, and to ship early and often, there is both vision reduction and tooling needed. That practice and training is vital to performance, and that practice must come on company time.   That working longer hours will make things worse; and adding people to the problem won’t deliver features faster; or that not correcting bad technical decisions has disastrous effects. We don’t have that metaphor, and without a good metaphor, it’s hard to have a shared understanding. We’re stuck with the same tools we’ve had: Build trust, ship, and use personal relationships to convince individuals of what works.  It’s not systemic, but it could work.

Microservices after Two Years

At this point, I have two(+) years of experience with Microservices, and I’m not an expert, but I have some hard-earned knowledge distilled from working with them (and making lots of mistakes in the process). Here’s what I learned that I wish I had known going into it.

Microservices are not mini-monoliths

Jim Gaffigan has a rather funny skit about (American) Mexican food. Listen to it here before I butcher the punchline. The punchline of the skit is all Mexican food basically consists of a tortilla with cheese, meat, or vegetables. We tend to think of deployable software in that same way. It’s all code, wrapped up with a deployment script, and sent to production. Monoliths are independent complete applications that fulfill a business function. So what’s a Microservice? An independent complete application that fulfills a business function. So why aren’t microservices just ‘mini-monoliths’? The answer comes from the idea that microservices collaborate. A monolith does not rely on another monolith for its uptime, data, or resiliency. It is generally a self-contained view of the world and due to their nature they do not care if anyone else exists. Your company’s website is wholly independent of anything else. More critically though, multiple teams may work on your company’s website. They share code, branches, and a single production pipeline. Microservices, on the other hand, are independent complete applications that fulfill a business function, but doesn’t fulfill more than one. A monolith does.

A Microservice understands that while it is independent, there are possibly zero or more people out there interested in what it has to say, and so it is designed with that understanding in mind. A Monolith is not, and does not have to be. Businesses eventually find out that they wish their monolith was designed to share its information in a de-coupled fashion, but often too late to do anything about it easily.

Microservices are not mini-monoliths; they’re collaborators that operate independently when they need to.

Microservices require a different way of thinking about problem solving

Developers love to write code. We’re so enamored with writing code that we’ll write code even when no one needs us to. We’ll write code to solve nagging problems on our own machines, or to automate silly things, or even write code to solve problems in our households. In fact, I have a new side project to set up a Raspberry Pi as a calendar viewer in my house. This is probably not unique to software development (though maybe it is? Do plumbers re-pipe their houses? Do electricians rewire theirs on a whim?) but the tenor of it is so overdone in software development that we exhort new developers to not write code first.

… And then we ask them to work on a monolith. Monoliths make writing more code easy. It gets to a point where the default state is “find problem”, “write code”, “ship”, without understanding whether or not the problem is best served by a bolt-on or add-on to the existing system. For small things this is not an emergent issue. Those small things can add up, and it will become a problem over time.

For instance, if you’ve ever tried to add a CSV import to any existing system , you’ve probably found out within days that the desired “CSV Import” feature is really a “CSV + Domain Specific Logic” import function, or almost as harmful is if a ‘bulk’ method of inserting wasn’t part of the original requirements; necessitating a change in the API. In a monolith; it’s really easy to write code to add this functionality that has baked in assumptions that aren’t clear, and to potentially change the API your system exposes, or how it presents itself to the user. Because of the ease of ‘just’ writing code, it it easy to rush the implementation without regards to the design. Writing code quickly is not the job; solving problems without causing more problems is the job; and a monolith makes that hard to do.

A user wants to add a stock to their portfolio…

Microservices, on the other hand, require up-front planning before code is written, every time. Every new service or any change to a service may be able to be coupled with completely replacing that service. Anything that has the potential to change the contract in a system (whether with the user or other services), requires more understanding and up-front design than the same change in a monolith. To go back to our CSV import example; a potential way of doing it with microservices is to have a new CSV importer service stood up that takes in a CSV file; does any Domain Specific Formatting; and emits an event or sends an HTTP request to the correct service and uses its existing API for adding/importing information.

And now they want to add multiple through CSV.

Now, these services are necessarily coupled to each other (though the coupling does goes in the right direction), and since the contract has not been changed for the original service; the guarantees of the original service are kept intact. Microservices make it harder to break existing consumers if done well. The trade-off is more upfront planning is required when designing a solution in a microservices based topology.

Domain boundaries are critical to Microservices success

There are three general flows to microservices (There may be more; but the types are escaping me right now):
1. Microservices that give new capabilities to an existing domain bounded context (the previous example of adding CSV import for a portfolio service as a separate microservice is an example of this — there are several trade-offs to doing that, and it depends on your constraints and desires)
2. Microservices that represent a stateless process (viz. validating a credit card)
3. Microservices that represent a stateful process or interaction (the portfolio service)

Notice that I said nothing about size of these services; and depending on whom you speak to, the size of a microservice is a mystery. I have opinions on this, of course; but the one invariant I’ve seen is that good microservices topologies ensure the lines are drawn at the domain’s “bounded context“. This is a fancy Domain Driven Design phrase that means to split up models and interactions by what they mean. To sales, a customer interaction is quite a different model and mode of interaction than a customer interaction for customer support. By splitting them up by their ‘context’ (and the boundaries being sales and customer support), the software can maintain independent ideas of how to interact with a customer depending on the context.

Martin Fowler’s Illustration of Bounded Contexts, source: https://martinfowler.com/bliki/BoundedContext.html


For microservices, this typically means that your customer support portal will be a different bounded context than your sales funnel; even if they share the same properties of a customer (at least demographically). There are three ways to handle the above problem:

Method 1: Set up a separate service with an independent customer model for each service (sales, customer support), and one created in one system is not necessarily referenced elsewhere (or it can be; customer_id, customer_support_id, sales_id)

Method 1, illustrated.

Method 2: Set up a “Customer” service, a sales service, and a customer support service, and both sales and customer support get customer information from the “customer” service.

Method 3: Set up a customer service, a sales service, and a customer support service; and sales and customer support have duplicated data (received through events) of things that happen in the customer service, but they maintain their own disparate models for what a customer means to them. From a system perspective the internal identifier is the same; how it’s used varies from system to system. This means having a customer service that has demographic information; a sales service that may or may not have this same demographic information but adds on sales context, and a customer support service that maintains this duplicate information but adds on its customer support pieces.

Each method has its own trade-offs; but you can quickly see the maintenance issues with each:

  1. Method 1 has three different representations of a customer; and potentially at different states in each service (a sales person sees a customer before they’ve signed on the dotted line, and a customer support person always has a “post sale” view of the customer. This is OK until you want sales to have the customer support information; and then you need to do a bit of juggling to ensure a customer from a sales context is indeed the same customer in a customer support context.
  2. Method 2 allows there to be one representation of a customer; and each service can either “add-on” to this representation of a customer; but each downstream service is still beholden to the customer service; and which context does that live in? Both. There is also a temporal coupling factor as each service “gets” demographic information from the customer service.
  3. Method 3 allows each service to be de-coupled from the “customer” service. It allows each service to add its own data to what it means for there to be a customer; and it allows each service to change independently (since each service will emit events it can listen to to update its model if it wants to). But this also means having a unified contract of what defines the demographics of a customer; and ensuring each service is set up to listen to events pertaining to customers, and each service appropriately handles being down if a customer event is emitted (event sourcing is a possible solution here).

None of these methods are “ideal” from an “easiest to develop” standpoint; and they have different levels of maintenance requirements. The one crucial decision that a team must make is what is the domain context, is this <thing> I’m dealing with talked about differently depending on who I talk to, and what is the maintenance cost of each approach. 

If the team chooses method #1, then they have a lot of distributed systems problems that aren’t easily solved; they’ve made interacting with the system harder. If they choose #2, then two services depend on a third (not really ‘independent’ at that point), and they’ve added an Request/Response dependency between services that may not need to exist (And is harder to debug). If they choose approach #3, they have quite a bit of upfront work (defining contracts; defining patterns), but the maintenance work, reasoning about how a service interacts with another service, debugging, and future expansion is far easier.

Developer Tooling doesn’t support Microservices as well as Monoliths

We have about 25 years of experience as an industry creating tooling around building and deploying software; though it’s only really in the last 15-18 years that the tooling has accelerated. But, even at 18 years of experience, we have pretty solid tooling around developing and debugging monoliths. Debuggers and IDEs take monoliths for-granted, as they likely should. If you write microservices that depend on other microservices over REST, you’re going to have a bad time debugging services locally. Your choices range from standing up the parts of the system that collaborate, or mocking out external dependencies, or dockerizing the system’s services so that they can be stood up independently. Of course, once you do this you’re diving into mixed networking land for Docker; and there’s not a lot of tooling that can make that experience seamless. A service running outside of docker that you’re debugging is hard to set up to work with services running inside of a docker network, or vice versa. Front-end development is even worse; as node.js is a requirement for building front-ends these days. Try live-debugging with docker for your UI where the source is kept locally. Not fun. Teams handle this problem in different ways; but the point is this problem exists, and the solutions are not as mature as debugging a monolith.

If you use microservices, you need to allocate a sizable chunk of time to building the tooling necessary to allow people to develop against those services.

Deployment requires better tooling with Microservices

Deployment considerations are key if you want a fast moving organization. You can’t respond to change without being able to change your software quickly. Even if you can develop changes quickly, if you can’t deploy them quickly you aren’t a fast-moving organization. Continuous Integration (CI) and Continuous Delivery (CD) is essential to being able to respond to change. These products reflect that the deployment view of the world is monolithic in nature. Source control is built for it, CI/CD systems are built around it; and pretty much every commercial CD system is built with monoliths in mind. There are several deployment models where microservices are used; and none of them have good tooling for microservices.

  1. Deploy on-premises as a packaged solution
  2. Deploy to the cloud independently
  3. Deploy to the cloud as a packaged solution

If you sell your product to customers, and they run it in their own data center, deployment method #1 is what you often deal with. Your solution must be packaged up and deployed together as a single unit. Should this necessitate that you develop as a monolith? No. It shouldn’t. However, if you have microservices, you necessarily have multiple deployable artifacts (whether they’re contained in a mono-repository (all services in one source control repository) or micro-repositories (each service in its own source control repository) is a separate matter), and your CD pipeline must take that into account. The trade-offs change whether it’s a micro-repository or mono-repository; but they still exist as problems not solved by current tooling. For instance, tagging master or a release branch with what is in production; or your promotion model to different internal environments; or even local deployments need to be taken into account by the tooling. If you choose method #2 and combine it with continuous delivery, some of those trade-offs go away; as you can make a rule that the latest in master is always pushed to internal promotion environments; and the only tag happens after a particular commit has been pushed to production; but again, tooling is still lacking to make this a seamless experience.

Microservices deliver on the promises of Object-Oriented Programming

I didn’t understand the hype of object oriented programming. I understood the fundamentals of encapsulation, abstraction, inheritance, message dispatching, and polymorphism, but I didn’t understand why they were so useful (I started with Perl, and then moved to Java, so I had nothing to compare Java’s OO nature to. At the time it just seemed like more work to do the same things I could do in Perl. Ahh, youth). The SOLID principles helped later on, but I always felt like there was more hype to OO than actual benefit. After several jobs maintaining and creating Object-Oriented solutions, I was convinced that Object Oriented Programming was a pipe-dream. To the 80% of us who are not “expert” programmers, it is a fad we can never make full use of and it causes more harm than good.

That was until I started researching microservices. This was it! A fully independent object that had agency that could collaborate with others; but encapsulation was ensured! The Open/Closed principle was a requirement! Single responsibility was almost ensured just by the nature of the service! (It says “micro” on the tin) Inheritance was far simpler — consume what the service gives you and modify it to suit your needs (the CSV example above). You couldn’t share information unless you had a common contract and used some sort of message dispatching!

This was absolutely huge for me. All of those principles that I’d been trying to bring to reality for years in codebases I’ve worked on were here — and best of all they didn’t have the downsides of OOP in practice! It’s really easy when modifying code to do something that breaks encapsulation, and business pressures make it even easier. With Microservices, that was no longer possible. Sure, other business induced pressures might cause problems, but they couldn’t alter the contract of a service; and that allowed the system to be reasoned about in ways OOP promised. Perhaps best of all, microservices put up guard rails that keep the mistakes of OOP from happening, and we’re all better for it.

Contracts, Patterns, and Practices should be Code generated

If you do something once, do it manually. If you do it twice, write down the steps, and do it manually. By the third time, automate it. Producing even a dozen services means either manually enforcing the structure of contracts
(the format by which services communicate with each other or to the user), patterns (how you structure common infrastructural concerns), and practices (how you write software) or code generating it for commonality. If you don’t code generate it, entropy wins. Even across features services start to do the same thing different ways; or you find new patterns for structuring your events, and depending on which service you’re in, you could see a different pattern. It’s untenable from a development and maintenance perspective.
Method #3 above shows a world where the Customer Service emits events when a customer is added or updated; allowing interested services to listen for changes and update their own data stores as necessary. Without code generation this would be a tedious process filled with error. With code generation and schema defined models; this is a viable development model.

Can you imagine trying to update any model/contract without code generation?


There are only two sane paths; package the commonalities (which can really only be done for dependencies) into utility functions, or code-generate everything.

Packaging utility classes/models (like the customer model and the events above); is a valid approach. The concerns with using it are taking on dependencies (even internal ones); the overhead of internal infrastructure; and the fact that every service would be required to be in the same programming language.
The latter path (code generation) is exactly what Michael Bryzek advocated in his talk Designing Microservices Architectures the Right Way and coming from trying the other paths (packaging common functionality, and doing it manually), I can see its utility. The trade-off, of course, is that developing the code generation tooling is a heavy investment of time. It requires discipline to develop this tooling first without trying to develop features; and it would likely result in no visible movement on things the business cares about (features, revenue, etc). It also ensures that as long as you have tooling to support that language, you can implement those models in any language you’d like.

You can’t punt on non-functional requirements

There are lots of non-functional requirements in a system that never appear on the roadmap, are never spoken about at the sales meetings, and are only tolerated by the product manager. Things like a user should be signed out after fifteen minutes; or the authorization system should incorporate roles and location; or some data is transient and not part of the backup strategy, and other data needs to be backed up every minute. Or, the system must allow 5000 concurrent users at a time. Those are non-functional requirements; they’re qualities of the system that aren’t part of the user-facing features being developed.

In a Monolith, there’s typically very few places to go to implement a non-functional requirement, and as we’ve discussed previously, IDE tooling is built for the refactoring necessary to ensure a change takes place everywhere it’s needed (only for the statically typed languages; the dynamic folks have their own problems to contend with), and even if you have to implement a new feature, there’s generally one place to do it.

Not so with microservices. If you implement authorization, you must implement it across all services. If you implement a timeout, you must implement it across all services. Unless your microservices are across hosts, any performance improvements must take into account that each service may share host resources with one or more other services. If each service is using the same server instance (i.e., every service that uses postgres shares a postgres server instance, even if they’re separate databases in that instance), then performance tuning and backups must take that into account. This greatly complicates matters of performance tuning and dealing with non-functional requirements; and for the system to be easily built, those non-functional requirements need to be known at the beginning! Every delay in implementing a non-functional requirement makes it more likely that some disparate changes will need to be made across several services; and that will take much longer once the services are built.

Event Driven Programming makes microservices work

In firmware programming, the finite state machine and events got me through the day. Each peripheral has separate states; and those are triggered by events that may happen from user input or other peripherals (for instance, seeing a bluetooth advertisement from a whitelisted address may trigger a connection). Since firmware by-and-large sits on a single core System-on-Chip with limited use of or no threads at all, using an event loop and finite-state-machines are one of the best ways to make firmware work.

Finite State Machines coupled with Event Driven programming also has other nice properties that parlay well into microservices: events ensure each service is de-coupled from the others (there are no direct request/responses between services); and Finite State Machines dictate what happens based on the current state of the service plus its input. This makes debugging a matter of knowing which state the service is in, and what input was received. That’s it. This greatly reduces the complexity in standing up and debugging services; and allows problems to be de-composed into events and states. If you add event sourcing into the mix, you have an event stream that records the events that occurred, so playing back issues is as simple as replaying events.

This is possible because microservices operate on network boundaries. In a monolith you’re forced to debug the entire monolith at once, and hope someone didn’t write code with disastrous side-effects that are impossible to find through normal means. It’s easier to find a needle in a small jar of needles than a giant haystack, and that’s possible because of the observable boundaries of microservices and using patterns that limit the amount complexity that allows you to arrive at a certain state.

If you’re going to start writing microservices; I highly recommend going down the path of event-driven programming, state machines, and some sort of event stream (even if you decide against event sourcing).

Choosing between REST and Events for supporting Microservices is tougher than you may think

If you’ve read the fallacies of distributed systems, then this section almost writes itself. Microservices are distributed systems, no matter how you shake it. One of the major problems when communicating across a network boundary is “is that service down, or am I just having a network timeout?” If you’re using REST, this means implementing the circuit-breaker pattern with some sort of timeout. It also means that if your services communicate to services that communicate to services through REST, then the availability in that chain will eventually hover just above zero. (00:00-12:31). As the video rightfully says, don’t do that. I’d go so far as to say that if at all possible; don’t make calls to other services through REST.

If you need data, have the service publish an event, and consume that event. This sounds great; it’s de-coupled, and it’s resilient to failure. However, each service must now have means to publish to a bus, consume an event off of a bus, and support whatever serialization scheme you want to use. Oh, and now you need to be able to debug all of the above. If you want runtime resiliency, you must sacrifice development simplicity to get there.

Maintaining Microservices requires strong organizational and technical leadership

“The business” does not care what the topology of your system is. They don’t care about its architecture, and they don’t care about how easy to maintain it is, any more than you care whether they use Excel or Quickbooks for forecasting. The business wants two things (really it’s n of 9 things) but work with me here:

  1. Increase Revenue
  2. Reduce costs

They believe more features will increase revenue. It’s a fair belief (correlation does not imply causation), but more features also increases development costs. To “the business”, the way to solve this problem is not by reducing the costs, but by increasing revenues. Again, this is also fair, and in a good number of cases is the right path.

Earlier, I mentioned that microservices keep those nasty shortcuts that cripple development teams from happening, and that’s a good thing, but, to the business, it can also be a bad thing. See, that crippling shortcut may never happen; but adding that feature (to their way of thinking) will increase revenue. If they have to choose between helping revenue but possibly hurting future maintenance, or delaying that feature by several weeks but helping future maintenance, they’ll pick the path to fastest revenue, every time.

The person or people that keep this from happening are hopefully the organization’s CTO and engineering leadership (VP or Director of Engineering, the Architect, and senior leaders of the team). They’re the people with the cachet and experience to know when this is going to hurt future maintenance, and they hopefully know enough to know it’s probably not a sure revenue bet either. But this requires discipline and trust on the part of the engineering leadership team. They must have gained the trust of the business by delivering what the business wants in the timeframe they want it; and they must be disciplined enough to stick to their guns. If someone says, “Well, we could do this in a week if we just hooked Service A up to Service B’s database”, you have now failed with microservices and are maintaining a future monolith. You’ve also lost the advantages of working with microservices.

Shortcuts are easy to say yes to, and shortcuts can greatly endanger the maintainability and health of a development team and the system.

Microservices are a technical solution to an organizational problem

While developers and consultants tend to espouse microservices in a cloud scenario, they tend to ignore that microservices are orthogonal to their deployment scenario, and they’re orthogonal to technology stacks. Take away all these advantages of microservices; and you’re still left with a topology that allows you to segment teams along domain boundaries, and have those teams operate independently of one another. At a small enough scale, you could even have individuals own services and scale out your feature creation to the number of people in your development organization. The Mythical Man month states that adding people to a late project makes it later; and it says that because those people have to communicate with each other. What if they didn’t? or what if you could reduce the amount of communication needed to ship a feature? Microservices let you do that. (I fall firmly in the micro-repository camp as well, so I’m about to conflate the two on purpose). Microservices development means independent repositories, and less issues with merge conflicts, branching, or collaboration needing to happen to push out a particular feature. It also means fewer avenues for the feature to clash with existing features; since by definition the service is independent and autonomous. It means fewer parts to reason about, and that results in faster development time.

Microservices (when architected well), let you go faster and further than you otherwise could, with less need to put organizational guardrails on the development team (code reviews; gated checkins, code freezes) to resolve team performance issues. It minimizes the effect a single developer can have against the whole system. This is a great benefit if the organization does not hire well or pay well (and if every organization did, we’d have a low turnover rate in software development), as it substitutes technology for some of the human training and improvements that organizations should do but don’t do.

If you have all top-notch performers in a high-performing engineering organization with a high performing business with no turnover, you don’t need microservices because you’re not going to make the mistakes that microservices would fix. If, however, you’re in an organization that consists of humans that are fallible, microservices provide a benefit to development that monoliths cannot.

Closing

Microservices are another tool to help make software development better and to make systems easier to maintain. They provide many benefits and have many trade-offs with traditional monoliths, and it’s rarely clear whether or not a system should be developed as a monolith or as microservices. There are several factors that can steer the choice towards one or the other; but those factors depend greatly on the individuals, organizational leadership, business model, constraints, and politics of the organization implementing those services.

These are the things I wish I had known when I started with microservices. What do you wish you had known about Microservices before working with them?

Note: Special thanks to Adam Maras for spending part of his weekend giving me feedback on this post.

Starting Again

As I typically do when I’m working remotely, I was getting an earlier start when I received a message from my manager, “I need you in the office today” in Slack. This itself was unusual, and since I was dealing with a water heater leak; the earliest I’d be able to get into the office was after lunch, and I said as much.

Naturally (and probably as a defense mechanism), I tweeted about it:

I went into the office after lunch, and yada yada yada, I resigned.

I tend to fully immerse myself into my work. Emily knows this and is very supportive, and also gently informs me when I’ve gotten too deep. This has happened several times in my career; and is probably best stated as a personal flaw wrapped as a short-term blessing to an employer. Let’s be very real: It’s not healthy, it’s destructive. The signs are the same for me each time:

  1. I find something I can identify with; be it a product, or the people, or the mission.
  2. I get the dopamine hit from belonging to that product/people/mission (“thing”).
  3. I identify with with that thing.
  4. I start to work more and more to ensure that thing is successful.
  5. I get in over my head; but since I’ve developed a reputation and set expectations that I’m always available; I can’t just ease-up overnight.
  6. I put my own interests outside of work aside; and work consumes my every waking thought. It is not a stretch to say that I’m literally working or thinking about working in every waking moment.
  7. My spouse and kids realize this.
  8. At this point; (as things often do), something is amiss in the work side too: (success is not linear).
  9. Things start to fail (small things); and the dopamine hits aren’t coming. Frustration mounts.
  10. I burn out; and become rather useless in my day to day (or night to night; since it affects my home-life too).
  11. Rinse, Lather, Repeat (often in the same organization, sometimes changing organizations).

I’ve known for a long time what I want out of life; I want financial freedom. I want to see my kids grow up. I want to enjoy each moment of my life. I don’t want to live to work; I want to work to live. This may seem foolish, I know, but think about any time you’ve worked for a company and their direction changed, and suddenly that thing you identified with no longer existed. Would you continue to wish you “lived to work” then?

I am fortunate to have time on my hands now, with the impending birth of our third child, to make my dream happen. And so my plan:

  1. Produce a business plan for what I want to do (short term, bring in revenue to fund my long term plan -> building a software business)
  2. Execute on that plan; revising as circumstances change.
  3. Long term; I want to build a software product business that is a great place to work for developers and also sustains itself and the lifestyle I want. I’m not looking to cash out, I’m looking to be moderately successful; and on the occasion that I’m lucky enough to employ people, I want them to be successful too. I don’t know what the software or the product looks like yet; but I do know what I want the business to be like.

With that in mind, I’m currently executing step 1. My wheelhouse is helping solve problems businesses have, and my specialty is using software to do it (or not using software, if able). This neatly aligns with my former job title of “Solutions Architect” and with the work I’m most used to doing. I also am shopping that around to see if there’s a market for an Independent Solutions Architect, targeting to solving the problems that small-to-medium businesses have. If it feels vague and fuzzy right now, that’s probably because it is. I am actively working to shape this vision into a market niche. If you’ve got any advice or feedback on this, please reach out. I’d love to hear from you.

I’m also brushing up on my networking skills. Something I’ve neglected for a long time is networking. Not because I didn’t want to (everyone wants to meet and know people, right?) but because it didn’t align closely with the successes I was having as a full-time employee and individual contributor. It is, as they say, a myopic view of the world.

With that, and with this newfound time, I want to give back in any way I can. Whether that’s mentoring, quick coffee chats (virtual or otherwise), or matching up developers and recruiters. I have a network of contacts (both on the recruiting side and programmer-y side); and if you’re either looking for developers as a recruiter or looking for good positions as a developer, I can help. As they say, my DMs are always open.

How do I compile Razor Views in .NET Core (CSProj)?

In .NET Core (project.json SDK Tooling), compiling Razor views was rather simple. Add this to your project.json:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.1.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Mvc": "1.1.0-preview1-final",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Design": {
      "version": "1.1.0-preview4-final",
      "type": "build"
    }
  },
  "tools": {
    "Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.Tools": {
      "version": "1.1.0-preview4-final"
    }
  }
}

And add this to the postpublish section:

"dotnet razor-precompile --configuration %publish:Configuration% --framework %publish:TargetFramework% --output-path %publish:OutputPath% %publish:ProjectPath%",

And it was done.
But with the CSProj version of .NET Core, they didn’t go back to the old CSProj method of doing that (would that have been too simple?) rather Microsoft introduced a new way to compile razor views.
To add RAzor compilation to .NET Core (CSProj edition), there are two things that need to be added:

  1. DotNetCliToolReference for a specific version of the CodeGeneration Tools.
  2. A new PropertyGroup containing the flag needed to compile Razor Views

For DotNetCliToolReference in .csproj:

    <ItemGroup>
      <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
    </ItemGroup>

And the Compile flag later:

  <PropertyGroup>
    <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
  </PropertyGroup>

And with that, each publish should include a compilation of razor views in the output.
I’ve found shockingly little in documentation for .NET Core Tooling (CSProj); but I did find this information from an issue linked to the aspnet/templates project on Github.
A note about the CodeGeneration tools; even though 1.0.0.0 is a later version than msbuild3-final; I tried 1.0.0.0 and it didn’t work; but the msbuild3-final did. I spent enough time monkeying with this that trying to reproduce it to submit a bug report seems like wasted time. I’m going to call it a victory and say “just use msbuild3-final.” Cargo-culty? Probably; but I’ve spent too much time getting .NET Core tooling to work to try to spend more time reproducing the issues.