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

<channel>
	<title>getiblog &#187; middle-end</title>
	<atom:link href="http://blog.getify.com/tag/middle-end/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.getify.com</link>
	<description>javascript, performance, and ui musings</description>
	<lastBuildDate>Thu, 15 Dec 2011 17:37:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>You&#8217;ve got your orange thing, I&#8217;ve got my square</title>
		<link>http://blog.getify.com/orange-vs-square/</link>
		<comments>http://blog.getify.com/orange-vs-square/#comments</comments>
		<pubDate>Thu, 11 Nov 2010 22:21:37 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance Optimization]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[server-side]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=666</guid>
		<description><![CDATA[If you haven&#8217;t noticed yet, almost every one of my blog posts starts out as a twitter conversation. There must be a pattern there. So, today, I&#8217;m going to address the bigger issues around the question I first asked, which started off the conversation, seems inefficient: emulating a DOM (built up w/ server-side JS)&#8230;which then [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t noticed yet, almost every one of my blog posts starts out as a <a href="http://twitter.com/#!/getify/status/2766997037252608">twitter</a> <a href="http://twitter.com/#!/getify/status/2768079054446592">conversation</a>. There must be a pattern there. <img src='http://getiblog.2static.it/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So, today, I&#8217;m going to address the bigger issues around the question I <a href="http://twitter.com/#!/getify/status/2760342438412289">first asked</a>, which started off the conversation, </p>
<blockquote><p>
seems inefficient: emulating a DOM (built up w/ server-side JS)&#8230;which then has to serialize into a html string, transfer, then be rebuilt.
</p></blockquote>
<p>though it turns out I had to <a href="http://twitter.com/#!/getify/status/2772140415778816">rephrase it</a>, because I got <a href="http://twitter.com/#!/getify/status/2770918904434689">answers to a different question</a> than what I asked.</p>
<blockquote><p>
rephrase: i get why server-side js is awesome (code reuse, prog enhnc, etc). why a DOM approach instead of shared/reusable templating?
</p></blockquote>
<h3>Tale of Two Questions</h3>
<p>For the sake of sanity and clarity, let&#8217;s break down the conversation into the two fundamental questions, and address them separately:</p>
<ol>
<li>Why is server-side JavaScript helpful for front-end/UI tasks?</li>
<li>Why would you use the DOM approach to the UI in server-side JavaScript as opposed to a templating approach?</li>
</ol>
<h3>Server-side UI</h3>
<p>There&#8217;s some really exciting things you can do with the UI of your web application with JavaScript. This is probably not news to anyone who hasn&#8217;t had their head under a rock for the last 5-8 years.</p>
<p>But what role (if any) can server-side JavaScript have in the question of how to use JavaScript in the front-end of your application? Certainly that seems like an oxymoron to be doing JavaScript in your &#8220;back-end&#8221; primarily for the benefit and use of your &#8220;front-end&#8221;.</p>
<p>In fact, this is <em>exactly</em> why I&#8217;ve been banging the loudest drums I can find to try to define the <a href="http://middleend.com">&#8220;middle-end&#8221;</a> (that is, what sits in between the front-end and back-end&#8230; the middle-end!) of the web application stack. </p>
<p>Specifically, there are a number of UI-related tasks which frequently occur in both places &#8212; the browser and the server. For instance: presentation &#8220;construction&#8221;, data/form validation (or data binding), etc. These tasks, along with others, I have defined as the &#8220;middle-end&#8221;.</p>
<p>Moreover, concepts such as &#8220;progressive enhancement&#8221; are heavily related &#8212; that is, the idea of progressively enhancing the presentation layer capabilities depending on the capabilities of the client making the request.</p>
<p>Where server-side JavaScript offers some really exciting answers is:</p>
<ol>
<li><strong>Code Reuse</strong>: If I can write my data validation code, or my UI construction code, etc, <em>once</em>, <strong>in JavaScript</strong>, and then reuse that code in both the browser and the server, I&#8217;ve significantly improved the maintainability of my application by achieving <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> (don&#8217;t repeat yourself).</li>
<li><strong>Progressive Enhancement</strong>: If I can take advantage of JavaScript&#8217;s ability to build out my page&#8217;s UI dynamically, I can achieve some really awesome things in the browser. But what about browsers which don&#8217;t have JavaScript (enabled)? The typical approach has been to serve a more basic version of the content to such less-capable browsers.
<p>But what if I could get most of the awesome benefits of JavaScript-powered presentation and not be affected by the browser&#8217;s inability to do JavaScript? What if I could run all my awesome JavaScript to build up my page (or even to dynamically alter it) on the server, and just send the HTML result of such operations over to a less-capable browser? To the user of such a browser, they might see things updating slower and a little less gracefully (with full page-refreshes), but they&#8217;d get most of the benefits of a dynamically capable page experience without having any JavaScript at all. </p>
<p>This could be a <strong>huge</strong> win for progressive-enhancement advocates, because it significantly reduces the amount of work that a site must do to provide some sort of alternate content experience for JavaScript-less browser users.</li>
</ol>
<p>These are not the only interesting ways that server-side JavaScript could be used to really revolutionize the web application process, but they should be more than enough to answer the question: &#8220;Why is server-side JavaScript helpful for front-end/UI tasks?&#8221;</p>
<h3>To DOM or not to DOM</h3>
<p>The meatier question in play here is, if we agree that server-side JavaScript should be used to improve the web application stack, should we choose a DOM-based approach to building out the UI on the server, or should we use a string-templated approach?</p>
<p>I&#8217;ll cut to the chase. <strong>The short answer is&#8230; BOTH!</strong></p>
<p>But the nuances of that assertion are what we&#8217;ll now focus on for the rest of this post.</p>
<h3>Oranges &#038; Squares</h3>
<p>Let&#8217;s first define more specifically what we mean by each distinct approach:</p>
<ol>
<li><strong>DOM approach</strong>: By this, I mean that you build up your page by explicitly creating each element as a node in a DOM tree. For instance, if I want to add this &lt;ol>&lt;/ol> ordered-list to my page, I first create an &#8220;ol&#8221; node, then I create an &#8220;li&#8221; node, then I append some text to the &#8220;li&#8221; node (as a &#8220;text&#8221; node of course), then I add the &#8220;li&#8221; node to the &#8220;ol&#8221; node, etc. Once my &#8220;ol&#8221; node is ready, I then append my &#8220;ol&#8221; node as a child element of some part of my page, like the current section I&#8217;m in.
<p>Such an approach might look like this (using jQuery):</p>
<pre class="code">
var $ol = $("&lt;ol>&lt;/ol>");
var $li = $("&lt;li>&lt;/li>");
$li.text("Some text");
$ol.append($li);
$("body").append($ol);
</pre>
<p>With this code, our JavaScript executes and programmatically builds up our DOM elements, eventually adding our &#8220;ol&#8221; element to the end of the &#8220;body&#8221; element.
</li>
<li><strong>Template approach</strong>: By contrast, here I mean that to build up the &#8220;ol&#8221; list as described above, you instead create a string like &#8220;&lt;ol>&#8221;, followed by a &#8220;&lt;li>&#8221;, then some text, then &#8220;&lt;/li>&#8221;, etc. Once the entire string of markup is done, then you insert that entire string into the page (or part of the page), either as the full HTML or as the <em>.innerHTML</em> of some element.
<p>Of course, I&#8217;m not suggesting that you literally have to manually add strings together with variables and such. That&#8217;s why we have template engines that do that for us. So, instead, you have a template like this:</p>
<pre class="code">
&lt;ol>
   &lt;li>{some_text}&lt;/li>
&lt;/ol>
</pre>
<p>With this &#8220;code&#8221;, our templating engine grabs the <code>{some_text}</code> part and replaces it with the value of that variable, and returns us the full constructed string, so we don&#8217;t have to mess with all the string operation details.</li>
</ol>
<h3>Zoom In</h3>
<p>So, let&#8217;s examine the differences between these approaches.</p>
<p>The first most obvious difference is what the &#8220;code&#8221; looks like that generates something visible in our presentation layer. In the DOM approach, large chunks (if not all) of your presentation layer is written in JavaScript <em>code</em>, usually tucked in with all the other front-end JavaScript. In the templating approach, almost all of your presentation layer is in HTML markup (as a string), usually in separate template files.</p>
<p>The result of building your UI in the DOM approach is an actual DOM tree (a physical nested object heirarchy in memory). The result of building your UI in the template approach is just a string of HTML markup.</p>
<p>Let&#8217;s be clear about something: <strong>a DOM is required to render something the user can see</strong> in the browser. So, the string of HTML markup that you get from the templating approach must of course eventually get parsed into a DOM tree.</p>
<p>That presents an obvious question: if a DOM is eventually required to actually <em>show</em> the presentation layer, isn&#8217;t it more efficient to just start out with (and stay in) the DOM tree, rather than going with string manipulation as a first stage of the process?</p>
<p>This is a fine and fair question. I hope I can quickly distill a few thoughts to suggest why I&#8217;m not so sure that the <em>obvious</em> is entirely correct &#8212; there&#8217;s more here than meets the eye.</p>
<h3>Designers</h3>
<p>Firstly, I&#8217;d suggest that there&#8217;s a pretty strong precedent for building HTML pages in&#8230; HTML. Designers, IDEs, and most web developers have learned and in many cases mastered the process of writing HTML markup. To my knowledge, almost none of the web development IDEs and typical processes are centered around an &#8220;(DOM)object-oriented&#8221; building of pages &#8212; in other words, I&#8217;ve never personally seen an IDE where when I look at source-view of a page, I&#8217;m messing around in a nested tree structure and adding and removing nodes.</p>
<p>Moreover, the very concept of a string of HTML markup actually conceptually representing a hierarchy of parent and child nodes is a very programmer-centric view. It&#8217;s like the difference between saying &#8220;The Quick Brown Fox&#8221; is a sentence phrase versus saying that, as a programmer, that&#8217;s actually an array of individual characters. Both are true, but one view is more semantic and the other is more programmatic.</p>
<p>So, stylistically, you can make a strong case (although it is ultimately preference-driven) that building out HTML pages is more natural and well-established as HTML markup as opposed to JavaScript code. From purely a role-separation standpoint, it&#8217;s perhaps more natural for UI designers (and the markup/CSS role) to be able to work in simple HTML markup than they will in code (whether that be JavaScript code, or some other back-end language code like PHP, Java, .NET, etc).</p>
<p>Just because we layer on a simple templating engine on top of the HTML markup to represent the concept of dropping in a dynamic data value in a certain location, doesn&#8217;t mean we&#8217;ve changed the paradigm from working with HTML markup to working with DOM nodes. Of course, some &#8220;templating engines&#8221; are far more complex, including all kinds of &#8220;programming-like&#8221; stuff, like conditionals, loops, function calls, arithmetic, boolean logic, etc. The more of that junk you cram into the &#8220;templating language&#8221; of your choice, the more like programming your presentation layer construction becomes.</p>
<p>As should probably be obvious, my strong preference is at the far simple end of the templating spectrum, where a bare minimum of anything that looks like &#8220;programming&#8221; is going on inside my HTML markup. I think that&#8217;s backed up by lots of precedence in &#8220;separation of concerns&#8221;, and I believe a lot of people agree. But there are others who prefer to write <em>code</em> to build up their presentation layer. To each his own, on that, I guess.</p>
<h3>Down To The Wire</h3>
<p>The other major difference, when we factor in such tasks as presentation layer building occurring on the server, is how the stuff that gets sent over the wire is prepared for the trip from the server to the browser.</p>
<p>In either the DOM or template approach, if the browser doesn&#8217;t have JavaScript enabled, the entire process of building the presentation layer occurs on the server, and what gets sent over the wire is always and only a string of HTML markup. The exact same page built with the DOM or template approach will end up being exactly identical when it squeezes down to fit through the pipe from server to browser &#8212; a string. </p>
<p>If we accept that in that base case, what transfers over the wire must be a string, then the question above of what&#8217;s more efficient (DOM or string) gets flipped. If the in-memory representation of the DOM (on the server) must first be down-converted to a string to be sent over the wire, <strong>this will tend to be less efficient than if the presentation layer is already (and only) just a string, ready to send.</strong></p>
<p>Now, what about the case where JavaScript <em>is</em> available on the browser? Assuming then that we&#8217;re in the part of a task where we want to off-load our presentation construction to the server, what gets sent over the wire is still going to be pretty much equivalent (though not the same). For the DOM approach, we&#8217;re going to send JavaScript, probably in the form of .js files, and in the template approach, we&#8217;re going to send HTML templates (strings), probably in the form of template text files. In each case, the files will be normatively cacheable to about the same extent.</p>
<h3>Run Time</h3>
<p>Both approaches are going to need JavaScript though, not just the DOM approach. The template approach is going to need a &#8220;template engine&#8221; that can do the same tasks that it did in the on-server scenario &#8212; do string operations and combine the string content with dynamic data. The DOM approach is going to need JavaScript logic to create, insert, append, and modify the in-memory DOM tree.</p>
<p>I don&#8217;t have conclusive statistics to suggest that either of those two JavaScript code logic paths are going to be substantially faster or more efficient than the other. String operations have, especially in recent JavaScript engines, become exceedingly optimized and fast (compared to really bad string performance in previous generations). Moreover, an intelligent template engine is going to &#8220;cache&#8221; the compilation of a template (that is, all the string parsing) into repeatedly-executable code, so the costly regular-expression-like parsing of the template string approach is going to be drastically reduced, considering the whole life time of the page view.</p>
<p>But let&#8217;s examine what happens at the moment when the presentation layer is about to cross the bridge and actually be added to the live DOM of the page. In other words, let&#8217;s compare whether it&#8217;s more efficient to inject a single ready string of markup via .innerHTML or to append a sub-tree of nodes to the main DOM tree. Fortunately, a <a href="http://jsperf.com">jsPerf</a> test exists to help answer this question: <a href="http://jsperf.com/dom-vs-innerhtml/10">DOM vs. innerHTML</a>.</p>
<p>I ran this test a few times in a few different browsers, and got conflicting results. In Webkit (Chrome/Safari), I got that the DOM insert was quicker (30-50% so) than the .innerHTML insert. But in FF (and to some extent, IE), I got the opposite. Opera was 40% faster at the .innerHTML than at the DOM insert. So, those results are mixed to say the least. I do however think it&#8217;s fair to say that as we would go back in time to older generations of browsers, the .innerHTML insert would tend to be a little faster, since most of the attention and focus in recent optimizations of the DOM has been in the DOM append operations. This is a conjecture at best on my part, but I think it&#8217;s not terribly inaccurate.</p>
<h3>Ideal vs. Realistic</h3>
<p>And let&#8217;s look closer at what&#8217;s going on in this test. The DOM insertion test case uses a <a href="https://developer.mozilla.org/En/DOM/DocumentFragment">DocumentFragment</a>, basically a temporary non-rendered DOM sub-tree, to append the children nodes to. Why go to this effort? Because it&#8217;s common knowledge that the absolute slowest part of anything you can do in JavaScript is the actual DOM manipulation against the live DOM of the page.</p>
<p>The reasons for this are varied, but include even things like how DOM manipulations require updating of internal live nodeList collections, force the rendering engine to do reflow and repaint, etc. So, if we can do all our DOM manipulation in a disconnected sub-tree without such side effects, we&#8217;ll drastically reduce the cost of DOM insertion. This is a well known and cited optimization technique that has very tangible effects. If that same jsPerf test were run without the use of DocumentFragment and were just inserting the children directly into the live DOM one at a time, <strong>the DOM insertion test case would have been hundreds or thousands of times slower across all browsers.</strong></p>
<p>So, are the DOM approach and template approach tied or inconclusive in terms of run-time performance? Perhaps. But I&#8217;d say maybe not. The test above represents the absolute best-case optimization, where you have everything you need for the DOM ready in a fragment, and can do it in one insert. In the real world complexity, you may have cases where you need to do 2, 3 or even 10 inserts all around a page. Because the overhead of the live DOM insert is, in general, much higher, the more of them you do, the quicker that negative performance will add up, and will be slower than the .innerHTML inserts.</p>
<h3>DOM > string</h3>
<p>There are a few cases where some valid arguments can be made that modifying the DOM dynamically is easier or better than dealing with HTML strings. </p>
<p>For one, whenever we&#8217;re dealing with event handlers (which get bound directly to DOM nodes), if you start re-assigning the innerHTML of nodes (or the entire page), you&#8217;re likely to screw up your event handlers. This is a common and costly mistake. It can of course be mitigated by the established best practices of using event bubbling/delegation, where you have event handlers bound only to top level DOM elements (like the body, for instance), which listen for bubbled-up events from any child elements &#8212; when you do it this way, you can freely re-create your elements using either DOM manipulation or innerHTML, and not mess up the event handling.</p>
<p>However, let&#8217;s keep in context what this post was about. If we&#8217;re talking about doing DOM building of a page on the server, we don&#8217;t have browser event handlers in place, so this problem is moot. </p>
<p>Another argument for the DOM approach is the ability to use CSS Selector Engine searching to find elements in the DOM tree. There&#8217;s no doubt that Selector Engines are extremely powerful, and using them to traverse through a DOM is equally so. But, when dealing with server-side DOM building, it&#8217;s less likely that you&#8217;re going to be layering on modifications to your DOM where you need to search the entire DOM repeatedly. For instance, you may be using the DOM approach, and you may &#8220;attach&#8221; a widget to the server DOM representation, where it creates a new set of DOM nodes to represent itself. But it probably won&#8217;t need significant CSS Selector Engine functionality to parse through the entire DOM when doing so &#8212; it&#8217;ll probably just operate locally in one area of the DOM.</p>
<p>And even if you did need to be able to push in different content into different places of your &#8220;page&#8221; (attaching different widgets), the regular expression&#8217;s power over string searching should be equally capable for most tasks. Your template engine can use a layered approach, where you have sub-template place holders for each widget, and you can tell the template-engine to build out each sub-template separately.</p>
<p>In short, there are cases where we may be more <em>used</em> to tasks (which we normally do in the browser) by using the DOM approach. But there&#8217;s not much if anything that can only be done with DOM and is impossible or impractical with string templating. It may take a slightly different mental shift to do so, but I believe templating can be every bit as useful (and perhaps even more so) as the DOM approach.</p>
<h3>Oranges AND Squares</h3>
<p>Let me wrap up this post with some final thoughts.</p>
<p>Firstly, as you&#8217;ve seen, there&#8217;s some awesome benefits to using server-side JavaScript to build your presentation layer UI. But more importantly, there&#8217;s more than one way to use server-side JavaScript to build it. You can use the DOM, you can use string templating, and you can do both in the same page as you see fit.</p>
<p>I&#8217;d just encourage you to realize that the DOM is merely a concept that the browser forced upon UI developers &#8212; it&#8217;s not actually the most natural way we deal with HTML for the presentation layer. The DOM API in the browser has some really ugly and non-performant warts, and yet some people are going to great efforts to emulate the DOM on the server. I wonder why we&#8217;re trying to shoe-horn the DOM into the server to accomplish our tasks, rather than using a string-templating approach that can work pretty naturally and capably in both places <strong>without any extra emulation layer</strong>?</p>
<p>But even if you&#8217;re unconvinced that the DOM is sort of an abnormal approach for the server-side presentation layer building, at least accept that both the DOM and templating approaches will serve you well. Pick which one (or both) is best for each task, and for each part of your development team. </p>
<p><strong>Don&#8217;t just assume that because YUI or jQuery are DOM-centric, that this is the only way to achieve server-side JavaScript presentation layer logic.</strong> A good, intelligent templating engine will give you all the same tools, and may just be a more natural and efficient fit in the long run.</p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/orange-vs-square/' addthis:title='You&#8217;ve got your orange thing, I&#8217;ve got my square '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/orange-vs-square/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Some better than none: sync vs. async in ssjs</title>
		<link>http://blog.getify.com/some-better-than-none-sync-async-ssjs/</link>
		<comments>http://blog.getify.com/some-better-than-none-sync-async-ssjs/#comments</comments>
		<pubDate>Mon, 25 Oct 2010 20:53:05 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance Optimization]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=622</guid>
		<description><![CDATA[This past week, I had a fantastic time travelling over to Warsaw, Poland for Front Trends 2010 conference. I was very honored to be invited to speak, and I gave the most recent incarnation of my talk on middle-end UI architecture, Rise of the Middle End (slides). Overall, the reaction in discussions over beer, feedback/ratings, [...]]]></description>
			<content:encoded><![CDATA[<p>This past week, I had a fantastic time travelling over to Warsaw, Poland for <a href="http://front-trends.com/">Front Trends 2010</a> conference. I was very honored to be invited to speak, and I gave the most recent incarnation of my talk on <a href="http://middleend.com">middle-end</a> UI architecture, <a href="http://front-trends.com/speakers#kyle-simpson">Rise of the Middle End</a> (<a href="http://www.slideshare.net/shadedecho/rise-of-the-middle-end">slides</a>).</p>
<p>Overall, the reaction in discussions over beer, <a href="http://speakerrate.com/talks/4871-rise-of-the-middle-end">feedback/ratings</a>, and tweets has been <a href="http://twitter.com/#!/bluecherry/status/28421536006">pretty</a> <a href="http://twitter.com/#!/matas_petrikas/status/28016533146">positive</a>. Even for those who seem to strongly <a href="http://twitter.com/#!/ls_n/status/28715874411">disagree</a> with my thoughts on this topic, I&#8217;m pleased that people are talking about it, which means they&#8217;re thinking about it, which means I accomplished my real goal: get people to start asking the right questions.</p>
<p>One of the most fascinating things to me was that immediately after I gave my talk, <a href="http://front-trends.com/speakers#douglas-crockford">Doug Crockford&#8217;s talk on server-side JavaScript</a> in some respects presented a very different view on things than my approach. So, back-to-back, two talks focused heavily on server-side JavaScript, and yet had a very different take on a key issue: synchronous vs. asynchronous.</p>
<p>After a <a href="http://twitter.com/#!/Mekk/status/28695990312">few twitter conversations</a> on the distinct differences between those two messages, I felt like it would be a good idea for me to write up a quick post to clearly state what I think about the sync/async debate, as I&#8217;m not sure it&#8217;s been well understood thus far.</p>
<h3>Crockford is right</h3>
<p>That&#8217;s correct, you did just read that. I think Doug is absolutely correct in his assertion that non-blocking I/O and asynchronous evented architecture are by far superior to synchronous, blocking I/O. There&#8217;s no question that JavaScript shines as an asynchronous language (despite the pains of us figuring out the right way to approach patterns like Promises), and so it&#8217;s a completely natural and right direction for Node.js to be taking server-side JavaScript into the asynchronous paradigm.</p>
<p>If I wasn&#8217;t clear enough, let me say it this way: <strong>async is better than sync.</strong></p>
<h3>Synchronous Middle-End?</h3>
<p>So wait, if I agree that the async Node.js approach is the best way, why do all my talks deal with synchronous JavaScript on the server via <a href="http://bikechainjs.com">BikechainJS</a>?</p>
<p style="background-color:lightblue;">
What you really need to understand is that just because you <em>run</em> code synchronously doesn&#8217;t mean that such code will <em>only</em> run in a synchronous environment. If you write the code correctly, which I&#8217;m trying to do, then synchronous vs. asynchronous execution concerns become rather moot. More on that later below.
</p>
<p>Again, let me be clear: <strong>BikechainJS is <em>not</em> intended to replace or compete with Node.js.</strong></p>
<p>BikechainJS and my synchronous per-request POC code/demos for the middle-end are merely side shows to the main attraction: the importance of middle-end architecture in the web stack.</p>
<p>Hear me on this: <strong>you should be architecting the middle-end into your web applications regardless of whether you use JavaScript on the server or not, and regardless of if you want/need to do things synchronously or asynchronously.</strong></p>
<h3>The back story</h3>
<p>So now, let me explain why I still am showing middle-end code demos using synchronous approaches.</p>
<p>Considering the variety of web application stacks I&#8217;ve worked in over the last several years, these architectures have ranged from Java to Grails to .NET to Python to PHP. The code bases have spanned from decent to horrible. Web performance optimization is always a tuning after-thought rather than a key business-driver feature. And the applications have all been built from the back-end up rather than the front-end down.</p>
<p>In all cases (and indeed for most of my 10 year web dev career thus far), some things have been true across the board:</p>
<ol>
<li>I&#8217;m a front-end/JavaScript person, and I prefer <em>not</em> to have to dig deep into the bowels of back-end platforms to accomplish my front-end tasks.</li>
<li>Universally, when I attempt to re-factor the front-end for web performance optimization, I run into the hassles of not having adequate control over the middle-end pieces (buried deep in the platform/framework guts), and moreover, I often have to deal unnecessarily directly with how the back-end works just to make changes to the front-end.</li>
<li>And most importantly, they have <strong>all</strong> been 100% in the synchronous, per-request paradigm of the web stack. They all used synchronous, single-threaded (process-oriented) web servers like Apache or IIS.</li>
</ol>
<p>That reality may not be your reality where you work. And if not, great. But having had a dozen jobs so far and seeing the same patterns repeated consistently, I&#8217;m willing to believe it&#8217;s more the norm than the exception that synchronous per-request is the overwhelmingly common paradigm, and that no matter how hard platforms/frameworks try to keep front-end and back-end separate, they all fail to do so well, when the rubber meets the road.</p>
<p>So, mentally walk in my shoes for a moment, in the types of jobs and environments I&#8217;ve been in for the majority of my career. The web application code bases are well established, and for the most part working <em>ok</em>. The boss(es), and 3-8 other devs on the team, are all pretty familiar with that paradigm. The IT support staff are all very familiar with the quirks and behaviors of that stack, and are in some cases quite experience/certified in how to manage it and ensure production up-time.</p>
<p>More than anything, stability and status-quo rule the pack.</p>
<h3>The plot thickens</h3>
<p>For my last several jobs over the last 2+ years (aka, long before Node.js came around), I&#8217;ve been trying to find a pragmatic way to introduce server-side JavaScript into the architectures of the web application stacks at my jobs. My goal has been to find a realistic way to address the middle-end failings of all these different web application stacks, especially in a repeatable and patterned way, and I feel that server-side JavaScript provides a very compelling answer to many of those questions.</p>
<p>Reality check: It is not particularly easy to introduce asynchronous code into a synchronous environment. It requires some very careful planning and often times some complicated and risky changes to existing architecture. In short: <strong>it messes with stability and the status quo.</strong></p>
<p>I&#8217;ve tried to pitch how server-side JavaScript can be of benefit, but whenever my boss or team starts to evaluate how to make that happen, major sticking points like that are always the death of the idea. For my jobs, their pragmatic (and defendable) position is that they would not be willing to devote the time to such radical rearchitecture (like replacing Apache with Node.js) and/or re-writes of significant portions (or all) of the code base, just to get JavaScript in the server part of the stack.</p>
<p>The biggest argument for server-side JavaScript at this point is massively scalable performance. But most of the jobs I work at never see enough performance bottlenecks where we could ever eventually prove the speedups in any measureable way.</p>
<p>All in all, I&#8217;ve had to face this reality in my jobs: <strong>if I want to do server-side JavaScript, I&#8217;m going to have to find a way to do it that fits more nicely into existing architecture and doesn&#8217;t cause quite so many waves.</strong> Otherwise, server-side JavaScript will only ever be something I get to toy around with on fun experiments like chat servers (web sockets) and games, and never see any real production usage.</p>
<h3>Swim with the current</h3>
<p>Instead of trying to simultaneously fight the battle of changing to asynchronous architecture <em>and</em> to switch to middle-end architecture using server-side JavaScript, I&#8217;ve chosen to separate those two battles and focus just on one of them for now.</p>
<p>What do I mean? There&#8217;s still an uphill battle to get server-side JavaScript into the stack in my real-world job place, but if it&#8217;s ever going to happen, it&#8217;s almost certainly going to need to play easily and nicely with the existing synchronous per-request paradigm.</p>
<p>Is it possible to use Node.js in this way? Theoretically, yes. You can run Node.js as a separate server instance, and from your synchronous code (PHP, Java, etc), make a blocking I/O call over to Node.js to ask it do something, and block the process waiting for the response. You can run Node.js like a proxy server in tandem with Apache, etc.</p>
<p>But notice what we&#8217;ve done: we&#8217;ve taken something whose almost entire value-proposition is performance from asynchronous eventing, and handcuffed it in an awkward and inefficient way to make it fit into our synchronous world.</p>
<p>In that respect, running synchronously against Node.js over an HTTP connection is not really conceptually much different than just running the JavaScript directly in a sub-process. It is however probably going to lose any possible performance benefits when considering the on-server overhead of making such HTTP requests as opposed to direct process execution/communication. Moreover, Node.js is phenomenally powerful and complicated, but restricting it in this way makes it be very much overkill for the simple things we want it to do.</p>
<h3>Switch into an easier gear</h3>
<p>After pushing about and thinking on these complications for quite awhile, that&#8217;s where BikechainJS was born. It&#8217;s an incredibly simple, stripped-down, highly-focused, synchronous, single-thread/single-process approach to running server-side JavaScript. It has only the bare minimum necessary to accomplish middle-end tasks, like file I/O, process execution, etc. It has NONE of the bells and whistles that make Node.js so sexy, but it also isn&#8217;t hampered by any of them getting in the way of its very specific task: run the middle-end.</p>
<p>BikechainJS is <strong>not</strong> what you want if you&#8217;re planning to write a significant amount (or all) of your server code in JavaScript. BikechainJS cannot do many of the most awesome things that Node.js can do.</p>
<p>But BikechainJS can easily be fired up to execute some simple JavaScript logic for middle-end tasks without creating too much overhead in your existing web stack and code. It has absolutely no dependencies except V8, and it&#8217;s just a single executable binary file. It&#8217;s footprint is extremely small, and it touches almost nothing that you don&#8217;t tell it to, which greatly reduces the risks involved in introducing it into your existing code.</p>
<p><strong>BikechainJS is not designed to replace Node.js, it&#8217;s designed to run in all the other places where Node.js is too awkward, risky, or difficult to implement.</strong></p>
<h3>Sync vs. Async</h3>
<p>It&#8217;s <strong>very important</strong> to note that just because I&#8217;m <em>currently</em> executing JavaScript in a synchronous way doesn&#8217;t meant the code itself is purely/only synchronous. </p>
<p>Most of the code I&#8217;m writing, I&#8217;m using Promises as a way to cleanly express logical steps which are reliant on each other, even if one of the steps is not immediate/synchronous. Using Promises, code can easily be written that will <strong>either work synchronously or asynchronously</strong> with little or no code changes at all.</p>
<p>You see, I obviously don&#8217;t want to needlessly tie my code to <em>having</em> to run in a synchronous way. I just want to execute my code synchronously, <strong>for now</strong>, so that it&#8217;s easier to integrate with the rest of the synchronous stack. That&#8217;s not so evil, is it?</p>
<p>You can very easily take a lot of this code and drop it into an asynchronous JavaScript environment like Node.js, and without much effort to adjust, it should run just fine. This is important in terms of future-proofing the code to be more useful as paradigms shift. I have the flexibility to run synchronous or asynchronous as the situation dictates. This is a very powerful realization.</p>
<h3>Putting it into practice</h3>
<p>How I am <em>currently</em> using this approach (and middle-end concepts) for my real-world job is to start to take little tiny pieces of the existing code, such as routing, headers, etc, and little by little, re-write them in JavaScript. In my existing web stack, when I want to hand off the execution context to my JavaScript code, I simply execute the BikechainJS environment and hand it some data and wait for the response. </p>
<p>Since the tasks it&#8217;s doing are very small and focused, it takes practically no time/overhead at all to do so (certainly way less than constructing and transmitting an HTTP request, even on-server, to a socket server instance).</p>
<p>Eventually, I hope that all of the middle-end logic in our app will be in BikechainJS driven middle-end JavaScript code. But I have the freedom to make the switch in very small chunks without major refactoring or rearchitecture. I&#8217;ve found a more plausible approach that my boss doesn&#8217;t get as worried about when I propose.</p>
<p>Bottom-line: <strong>I&#8217;ve found a way to introduce server-side JavaScript to an environment that otherwise flatly rejected the notion of a major sync-to-async rearchitecture.</strong> I believe that some server-side JavaScript is better than none at all.</p>
<p>I secretly hope that this move will be just a &#8220;gateway drug&#8221;, and that eventually, we can move to a much more powerful and asynchronous approach to our middle-end <em>and</em> back-end, probably using Node.js. Because I&#8217;ve written most of my code to be agnostic of such concerns, such a switch down the road shouldn&#8217;t be as painful as it otherwise might have been. We&#8217;ll already be more than halfway there with server-side JavaScript in the stack, and introducing asynchronous architecture patterns (while challenging) won&#8217;t necessarily be impossible to sell to the decision makers.</p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/some-better-than-none-sync-async-ssjs/' addthis:title='Some better than none: sync vs. async in ssjs '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/some-better-than-none-sync-async-ssjs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JSConf 2010 &#8211; getify on middle-end/ui architecture</title>
		<link>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/</link>
		<comments>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/#comments</comments>
		<pubDate>Tue, 03 Aug 2010 18:25:10 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui architecture]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=516</guid>
		<description><![CDATA[JSConf 2010, Track B, "Dude, Where's My UI Architecture?"]]></description>
			<content:encoded><![CDATA[<p><embed src="http://blip.tv/play/g_MngemSLgI%2Em4v" type="application/x-shockwave-flash" width="480" height="346" allowscriptaccess="always" allowfullscreen="true"></embed></p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/' addthis:title='JSConf 2010 &#8211; getify on middle-end/ui architecture '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/jsconf-2010-getify-on-middle-endui-architecture/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Node.js: The end of the middle?</title>
		<link>http://blog.getify.com/node-js-the-end-of-the-middle/</link>
		<comments>http://blog.getify.com/node-js-the-end-of-the-middle/#comments</comments>
		<pubDate>Sun, 18 Jul 2010 19:30:29 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=480</guid>
		<description><![CDATA[If you haven&#8217;t yet read my ode to why Node.js is awesome, stop and go do so now. It should be no surprise by now that I am giddy like a school girl over the idea of using server-side JavaScript to revolutionize the web application stack. And perhaps no other project has captured more of [...]]]></description>
			<content:encoded><![CDATA[<p>If you haven&#8217;t yet read my <a href="http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end">ode to why Node.js is awesome</a>, stop and go do so now. It should be no surprise by now that I am giddy like a school girl over the idea of using server-side JavaScript to revolutionize the web application stack. And perhaps no other project has captured more of the imagination and zealotry from the JavaScript developer community as <a href="http://nodejs.org">Node.js</a> has over the last 6-9 months. It&#8217;s undeniable that Node.js will continue to be one of the most important players in this emerging &#8220;market&#8221;.</p>
<p>But silver-bullet or the second-coming of the web? I&#8217;m not so sure Node.js can quite claim that status. Here, we&#8217;ll investigate the counter-point to Node.js, especially as it relates to practical usage in the middle-end. Raining on the parade may not be fun, but if we&#8217;re gonna gulp down the delicious Node.js grape kool-aid, we&#8217;re also gonna have to stomach a healthy amount of that ick-tasting Node.js cough syrup (that&#8217;s right, I just mixed 3 metaphors in one sentence!). We owe this topic some intellectual honesty and debate.</p>
<h4>Brad Pitt in &#8220;Interview with a devil&#8221;</h4>
<p>I want to (re)introduce you to a good friend of mine. He&#8217;s exceedingly well known, and I&#8217;m sure you&#8217;ve met him many times before. He&#8217;s not a popular guy by any means &#8212; probably more infamous than famous &#8212; but he can be very assistive in times when the hype of something <em>new</em> clouds our judgement of the things we already <em>knew</em> well.</p>
<p><span class="me"><strong>Me:</strong> Devil&#8217;s Advocate (&#8220;DA&#8221;), welcome to the show. I&#8217;m glad you could join us for this discussion today.</span></p>
<p><strong>DA:</strong> Thank you for inviting me over for some tea and a lively discussion. You know how much I enjoy calmly reminding people of reality, and in the process spoiling a lot of their fun.</p>
<p><span class="me"><strong>Me:</strong> DA, are you saying you <em>like</em> being the least popular guy at the party? A lot of people think you are a Contrarian&#8230; that you just like to disagree for the sake of disagreement, and that you don&#8217;t really <em>help</em> the discourse very much. What do you think of that characterization?</span></p>
<p><strong>DA:</strong> Well, that&#8217;s true that most people probably think of me that way. But that&#8217;s ok, I am secure in my manhood and it doesn&#8217;t bother me that much. I&#8217;m used to intellectual rejection. I mean, look at how hard I&#8217;ve been working to try and wake people up to Apple&#8217;s antics with the iPhone 4 antenna, and yet the masses still cling to Jobs&#8217; every word like he&#8217;s a prophet or&#8230;</p>
<p><span class="me"><strong>Me:</strong> Ok, DA. Let&#8217;s not get off on that tangent here. That <em>is</em> a fun topic, but we&#8217;ve got more important things to deal with today.</span></p>
<p><strong>DA:</strong> Sorry, sometimes I just get carried away. But I do think my methods are helpful in encouraging people to question certain assumptions and make sure that all sides of a topic have been examined thoroughly.</p>
<h4>Hello World</h4>
<p><span class="me"><strong>Me:</strong> That&#8217;s good. Let&#8217;s jump right in. I know you read my previous post where I gushed over how awesome Node.js is and where I explored how it might fit with the middle-end concepts I&#8217;m advocating for.</span></p>
<p><strong>DA:</strong> Of course. I wrote that little editorial sidebar as a preview of our discussion today.</p>
<p><span class="me"><strong>Me:</strong> Right. So, tell the readers, what do you think of Node.js?</span></p>
<p><strong>DA:</strong> It&#8217;s awesome. Really it is. But it&#8217;s awesome for a specific set of tasks and for a specific kind of scenario. We have to be careful to remember that even though it&#8217;s very exciting for developers to jump on board and start experimenting with a new implementation like Node.js, that doesn&#8217;t mean in any way that it&#8217;s going to work for everyone.</p>
<p><span class="me"><strong>Me:</strong> Obviously not, no one technology is ever right for everyone. I don&#8217;t think anyone is suggesting that. Seems like you&#8217;re just chewing on the soggy cheerios.</span></p>
<p><strong>DA:</strong> No, it&#8217;s more than that. I&#8217;m actually trying to help people realize <em>exactly</em> what Node.js <em>is</em> and <em>is not</em>, so that we can have productive discussions not only about Node.js and its uses, but <em>also</em> about other alternatives for the rest of the crowd.</p>
<p><span class="me"><strong>Me:</strong> Don&#8217;t you think it&#8217;s just too early to be judging what Node.js can and cannot do? I mean, isn&#8217;t it possible that it&#8217;ll grow to be useful in more parts of the stack as time goes on?</span></p>
<p><strong>DA:</strong> It&#8217;s entirely possible and likely that Node.js will continue to grow in popularity, and more and more waves of developers will find innovative uses for it. But I don&#8217;t necessarily think that means it will ever win over the minds of conservative, established and slow-to-change development teams &#8212; and especially their bosses and IT support staff.</p>
<p><span class="me"><strong>Me:</strong> Why not?</span></p>
<p><strong>DA:</strong> It&#8217;s purely pragmatism, I feel. I&#8217;m considering the <em>majority</em> of the web application universe to be of the sort that is not naturally bleeding-edge (even if the bleeding edge is awesome) and often follows well behind the curve, and sometimes never follows at all. I&#8217;m thinking of the millions of PHP shops, and the Java shops, and lord knows the .NET shops&#8230; all of them out there, chugging along in their own little world. That world is not likely to be &#8220;rocked&#8221; (as you called it) by Node.js or even server-side JavaScript.</p>
<p>The payoff for them re-writing most or all of their current code base (whatever language it is) into server-side JavaScript would have to be epic and enormous, almost beyond adequate description in words, to convince them it&#8217;s worth all the time, money, and <em>risk</em> such a venture would entail.</p>
<h4>Change you can believe in?</h4>
<p><span class="me"><strong>Me:</strong> OK, fair enough, a lot of them might be resistant to change. But aren&#8217;t all new technologies up against that same battle at first? The ones that eventually prevail do so despite the nay-sayers (like you) from the early days.</span></p>
<p><strong>DA:</strong> On the surface, you&#8217;re correct. But again, I&#8217;m talking about something much deeper and more fundamental than just: will the masses ever accept server-side JavaScript? </p>
<p>In fact, I think that&#8217;s really <em>your</em> biggest question to answer as you try and convince people to embrace the middle-end with server-side JavaScript as the driving technology. Yes, the middle-end as a concept doesn&#8217;t require JavaScript, but the biggest payoffs in the middle-end come if people will accept server-side JavaScript into the stack. You&#8217;ve got a big uphill battle even trying to convince people that a little tiny piece of the stack can be done adequately with server-side JavaScript.</p>
<p><span class="me"><strong>Me:</strong> Thank you for reminding me just how challenging this is.</span></p>
<p><strong>DA:</strong> My bigger point is, Node.js at its fullest is much broader than I think most people realize. I think it represents a paradigm shift, not just the introduction of an existing technology into a new environment. </p>
<p>I think I&#8217;d liken this concept to trying to convince a company that makes desktop video-editing software that the new age will be their software web/cloud-based and mobile. Noone would argue that the mobile and cloud movements are huge and clearly represent the future. But the desktop application company is probably still likely to adhere to their core competency and continue to serve and rely on the paradigm of desktop application and hardware.</p>
<p>And they may rightly argue that the payoff for being able to take even part of their awesome video-editing functionality and stick it on a tiny screen device with 1/100th the CPU power probably doesn&#8217;t justify the efforts to try and get on the bandwagon with &#8220;everyone else&#8221;.</p>
<p><span class="me"><strong>Me:</strong> A paradigm shift? Can you elaborate?</span></p>
<p><strong>DA:</strong> Here&#8217;s what I mean: Node.js is not <em>just</em> an execution environment for server-side JavaScript. In theory, you <em>could</em> just run JavaScript on the server in an on-demand way, as needed. And I bet Node.js would be pretty decent at that task.</p>
<p>But by even thinking about Node.js in that light, you&#8217;ve drastically missed the point of what it&#8217;s trying to do. Node.js is trying to leverage the asynchronous power of JavaScript at a deeper level than on-demand application logic. Node.js is trying to <em>become</em> the network server itself, so that the server-side JavaScript you write for your application can be interpreted in a much more natural and almost native way.</p>
<p>Let&#8217;s look at this in light of some more established existing functionality. Consider a PHP web application. Now consider there&#8217;s some additional &#8220;module&#8221; for some task, like for instance doing OpenSSL encryption/decryption. There&#8217;s multiple ways your PHP code could accomplish this task. We know there&#8217;s command-line utilities (written in C and compiled to binaries) for managing OpenSSL. So, from our PHP, we can call out to those binaries by executing them as sub-processes.</p>
<p>But this isn&#8217;t necessarily the most efficient way to do things. It certainly <em>can</em> make code look less graceful and more complicated to maintain (more moving parts). Instead, we&#8217;d like it if someone could write a PHP &#8220;extension&#8221; that brings the capabilities of the OpenSSL engine natively into our PHP code. Coding against a PHP API for OpenSSL feels more natural than executing a binary sub-process, and it&#8217;s also likely to be a lot more performant.</p>
<p><span class="me"><strong>Me:</strong> That sounds about right.</span></p>
<p>I can&#8217;t speak for the designers of Node.js, but I&#8217;d venture that among their various motivations, they wanted to do something similar (but in a much broader sense) for server-side JavaScript in the web stack. They wanted to make coding <strong>your entire application in JavaScript on the server</strong> as natural and native and built-in feeling as doing any other task in the web server, including listening for requests on port 80, doing file I/O, etc.</p>
<p>You see, the different paradigm that Node.js is bringing to the table is the idea that the web server and the application become almost synonymous. I think more than anything, <em>that</em> is the truly compelling story for Node.js. I&#8217;m not saying that Node.js is the <em>first</em> to do this, but I do think that Node.js is the most radical approach in this area that we&#8217;ve seen thus far.</p>
<h4>Vive la RÃ©volution!</h4>
<p><span class="me"><strong>Me:</strong> Ok, so that does sound pretty revolutionary. But I missed the part about how this <em>doesn&#8217;t</em> fit well with the middle-end.</span></p>
<p><strong>DA:</strong> Well, you certainly are the primary advocate for the middle-end, so I won&#8217;t try to speak for you. But, I think you and I have some parallel thoughts in mind at this point, even if you don&#8217;t realize it. <em>You</em> have a vested interest (by virtue of your efforts to call attention to the middle-end) in convincing the &#8220;world&#8221; to adopt middle-end architecture as an intentional and carefully planned layer. The more applications/teams that do so, the more you will &#8220;prove&#8221; that middle-end architecture <em>needs</em> to be its own discipline and not just an after-thought of existing platforms/frameworks.</p>
<p>I&#8217;m trying to suggest that Node.js represents a fundamental shift in how people will think about web servers and applications, not as separate functional units but as conjoined parts of the same whole. A web application no longer has to be thought of as a set of business logic code and pretty HTML that relies on a web server to send it to users. A web application is fully self-contained and capable of doing everything it needs from within itself. And it uses a consistent language (JavaScript) to do everything throughout.</p>
<p>This idea is so radical that I think most web applications and platforms and companies will have a hard time swallowing it, at least any time in the relevant future. Thus, I submit that a &#8220;middle-end&#8221; that relies on Node.js will be less palatable to the masses than a &#8220;middle-end&#8221; that is more agnostic and flexible.</p>
<p><span class="me"><strong>Me:</strong> Right, I&#8217;ve tried to make the point that the middle-end as an architectural pattern doesn&#8217;t <em>have</em> to have JavaScript on the server involved. Really, the primary reason for why server-side JavaScript offers an interesting answer to the middle-end is the idea that we can write code once and re-use it in both server and browser. No other language/technology can ubiquitously offer that.</span></p>
<p><strong>DA:</strong> Exactly. You see, Node.js represents a <em>particular</em> narrowed down implementation of the broader middle-end concept into one specific form. That form happens to be increasingly exciting to the bleeding edge of the web development community, but I foresee problems in truly convincing the establishment that both Node.js <em>and</em> the middle-end together will be right for them.</p>
<p>Take the Chrome browser for example. It&#8217;s got a huge percentage of market-share among open web developers. Along with Firefox, Chrome is quite obviously becoming a web developer&#8217;s browser of choice. But when taken in the overall context of the web, Chrome&#8217;s percentage is still pretty low. There&#8217;s an established momentum around browsers like IE and Safari, and Chrome is not likely to completely overtake them any time in the foreseeable future.</p>
<p>Node.js is an amazing piece of technology. But it&#8217;s almost <em>too</em> amazing for the middle-end. It certainly will be more radical to convince existing applications to embrace the fullness of what Node.js is than it would be to suggest, as you have many times, that a more simple, stripped down approach to server-side JavaScript is possible, and in fact warranted.</p>
<h4>Army of none</h4>
<p><span class="me"><strong>Me:</strong> Why isn&#8217;t using Node.js in a more limited fashion (like on-demand or per-request as you suggest) a valid usage of Node.js?</span></p>
<p><strong>DA:</strong> I wouldn&#8217;t call it invalid. I&#8217;d just say that it&#8217;s a lot like driving a tank down to the corner store to buy some drinks. Can it get you there? Sure. Will it get the task done? Yes. Is that an effective mode of transportation? Perhaps not.</p>
<p>Some people like to argue that because Node.js has all this amazing capability built into it, it&#8217;d be foolish to not use it for your server-side JavaScript tasks because of all the extra stuff you&#8217;d miss out on if you ever decided later you needed it. This is kind of like arguing for taking the tank for the trip down to the corner store because you want to be prepared in case an invading army of aliens attacks. &#8220;Look, I&#8217;m better prepared to fight off the bad guys in my tank than I am on my little scooter.&#8221;</p>
<p><span class="me"><strong>Me:</strong> Don&#8217;t you think that&#8217;s just a little bit of an exaggeration?</span></p>
<p><strong>DA:</strong> Well, maybe a little hyperbole there. But my point remains, Node.js is way overkill for the simple middle-end tasks at hand. If someone is trying to shoehorn using Node.js into doing simple per-request on-demand JavaScript execution (the likes of which you&#8217;ve argued for in the middle-end), they are really missing the point of Node.js. </p>
<p>To put it another way: <strong>they&#8217;re using a sledge hammer to drive in a thumbtack.</strong></p>
<p><span class="me"><strong>Me:</strong> Isn&#8217;t there something to be said for using a project like Node.js for our tasks, because at least it&#8217;s pretty well known and has a lot of active developers and a vibrant support community?</span></p>
<p><strong>DA:</strong> No question, it seems like using Node.js would be the obvious choice for this task. And <strong>perhaps</strong> a developer might be better able to convince their boss to try Node.js at first than some much less known project like your <a href="http://github.com/getify/BikechainJS">BikechainJS</a> option.</p>
<p>But in the long run, I think that <strong>using the right tools for the job always wins</strong> out in terms of efficiency and maintainability over using the more popular or hyped solutions and later on finding it&#8217;s not a good fit.</p>
<p><span class="me"><strong>Me:</strong> If one of those &#8220;established&#8221; companies <em>was</em> going to broaden their horizons, isn&#8217;t it riskier for them to venture off into the wilderness and choose an unknown project/option as compared to sticking closer to home with something more people know better?</span></p>
<p><strong>DA:</strong> It may <em>appear</em> riskier. And definitely perception is hugely important in this game. But in reality, Node.js is actually asking an existing team/platform to put more of their eggs in the server-side JavaScript basket than what you&#8217;ve argued for in the stripped-down middle-end approach. </p>
<p>Like I said earlier, Node.js is a fundamental paradigm shift. This means that companies are going to have to retool a big portion of their web stack. They&#8217;re going to have to train IT support staff on a whole new set of technologies in the web stack. They throw out their 5, 10, 15 years of experience supporting and performance tuning traditional synchronous web servers like Apache, and now they have to learn it all again with a radically different asynchronous server-side JavaScript web server. I shouldn&#8217;t have to point out what a &#8220;shock&#8221; that would probably be to most organizations.</p>
<p>And the risk doesn&#8217;t stop there. Node.js itself is ever-changing. It&#8217;s stabilizing more recently, but it&#8217;s been incredibly volatile. I&#8217;d say right now it&#8217;s like walking over a bed of molten volcano lava that only a few hours ago started cooling and hardening into volcanic rock. How much do <em>you</em> trust that an inch of cooled volcanic rock is enough to protect you (and your 800 lb elephant) from the river of lava just below the surface?</p>
<p><span class="me"><strong>Me:</strong> Doesn&#8217;t <a href="http://www.commonjs.org/">CommonJS</a> offer us hope of stability and compatibility?</span></p>
<p><strong>DA:</strong> Absolutely, it promises that. But it may be literally <em>years</em> before there&#8217;s consensus in the server-side JavaScript world on how all these API&#8217;s should really look and function. In fact, if the browser API&#8217;s have taught us anything, we may <em>never</em> fully have agreement.</p>
<p>Now, certainly the browser irregularities didn&#8217;t sideline 10&#8242;s of millions of companies from leaping into web applications, but most of them didn&#8217;t dare venture into the game until there was at least some sort of reasonable &#8220;gap fill&#8221; like any of the various JavaScript frameworks, which normalize differences across browsers and provide a stable foundation for companies to build upon.</p>
<p>So it may be awhile before CommonJS and/or some set of server-side JavaScript &#8220;frameworks&#8221; are able to secure a stable footing. If you look at Node.js right now, it represents a significant super-set of the small amount that CommonJS participants have &#8220;agreed&#8221; on. So, marrying yourself to Node.js right now is risky because it&#8217;s like marrying your web application to only FF and hoping that its rampant popularity will be enough to drive everyone else to commonality.</p>
<h4>Fatalism: a cruel mistress</h4>
<p><span class="me"><strong>Me:</strong> So can we really do <em>anything</em> with server-side JavaScript at this point, given the immaturity and instability across the board?</span></p>
<p><strong>DA:</strong> Of course! I&#8217;m not at all suggesting Node.js is bad to use because its unstable. I&#8217;m suggesting it has its places where it&#8217;s a natural fit (like in prototypes, developer experiments, and other flexibile-to-change dev environments), and then it also has places it&#8217;s not a good fit (like established teams with slow-to-change environments).</p>
<p>The same would be true of any server-side JavaScript option at this point, in my opinion. Of course there&#8217;s the obligatory &#8220;use-at-your-own-risk&#8221; label on all such things. But the smaller, more independent, and more custom your server-side JavaScript implementations are, the more likely you are to be able to adjust as the &#8220;industry&#8221; matures and changes.</p>
<p>At this point, if you were to go out and re-write your entire application in Node.js&#8217;s flavor of server-side JavaScript, you could be painting yourself in a corner if what evolves over the next few years is not in line with how Node.js is currently doing things.</p>
<p>My point is that the smaller the footprint of your server-side JavaScript at this point, the more insulated you are from these risks. Whereas Node.js represents a pretty big footprint conceptually, using stripped-down, per-request, on-demand JavaScript solutions represents a much smaller footprint both technologically and conceptually. Companies are more easily able to integrate such things little-by-little, and also strip them out if problems arise. A re-architecture to Node.js and server-side JavaScript would both be more comprehensive and also more difficult to undo.</p>
<h4>Parting shots</h4>
<p><span class="me"><strong>Me:</strong> We&#8217;re almost out of time&#8230; do you have any final thoughts to share or clarify with the audience regarding Node.js and the middle-end?</span></p>
<p><strong>DA:</strong> I think your idea of <a href="http://blog.getify.com/2010/07/why-node-js-rocks-the-middle-end">using Node.js as a go-between &#8220;proxy&#8221; for middle-end tasks</a> is an interesting one. I think it represents probably the best possible scenario in which Node.js fits in with your &#8220;middle-end&#8221;.</p>
<p>But I&#8217;ll close by saying this: you must realize that Node.js may in fact be ushering in, at least for those (few) who are inclined and capable of taking up the banner, a new era of web applications. This era will be one defined by a blurring of the lines between front-end, middle-end, and back-end code. It will be a new class of web applications that is built end-to-end in JavaScript. In such a world, the middle-end tasks become the all-end tasks. So, more than anything, I think Node.js may mean there&#8217;s no need for a middle-end any more.</p>
<p>However, I think the reality is there will only ever be a select enlightened few who ever get to fully explore that new paradigm. For the overwhelming majority &#8220;rest of us&#8221;, the &#8220;middle-end&#8221; will still be a valid and important reality for our web applications, and as such, we should embrace this discussion.</p>
<p><span class="me"><strong>Me:</strong> Well said. I have nothing more to add, except a thank you to DA for joining us today. I know you&#8217;re a busy guy, so I&#8217;ll let you get on to other pressing debates.</span></p>
<style>.me { color:#663322; }</style>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/node-js-the-end-of-the-middle/' addthis:title='Node.js: The end of the middle? '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/node-js-the-end-of-the-middle/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why Node.js rocks the middle-end</title>
		<link>http://blog.getify.com/why-node-js-rocks-the-middle-end/</link>
		<comments>http://blog.getify.com/why-node-js-rocks-the-middle-end/#comments</comments>
		<pubDate>Thu, 15 Jul 2010 21:08:20 +0000</pubDate>
		<dc:creator>getify</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI Architecture]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[middle-end]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[ui]]></category>

		<guid isPermaLink="false">http://blog.getify.com/?p=467</guid>
		<description><![CDATA[If you&#8217;re even moderately involved in the JavaScript world these days (and you probably are if you&#8217;re reading this blog) you would have to be dead asleep to not have noticed and heard some of the hype and celebration for the poster-child for server-side JavaScript: Node.js. I regularly follow the chatter on the interwebs, and [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re even moderately involved in the JavaScript world these days (and you probably are if you&#8217;re reading this blog) you would have to be dead asleep to not have noticed and heard some of the hype and celebration for the poster-child for server-side JavaScript: <a href="http://nodejs.org/">Node.js</a>. </p>
<p>I regularly follow the chatter on the interwebs, and I&#8217;m amazed and thrilled at just how much gravity Node.js has accumulated in terms of developer excitement and <em>actual</em> project input. In fact, in some ways, the Node.js ecosystem of companion projects is even more awesome than Node.js itself! It&#8217;s a fantastic example of how the community was desperate for something (we didn&#8217;t even know exactly what) and how well we quickly rallied around <em>it</em> when we finally found it. It&#8217;s plainly obvious that server-side JavaScript is an idea whose time has come, and Node.js, in many ways, will take us there.</p>
<p>This post is an attempt to put my little niche spin on what Node.js <em>could</em> mean for someone wanting to tackle re-architecting <a href="http://middleend.com">the middle-end</a> of their web application.</p>
<h4>What is Node.js?</h4>
<p>In the broadest terms, Node.js is an application server platform. It&#8217;s actually a server-side JavaScript execution environment (roughly similar to something like Narwhal) wrapped around the V8 JavaScript engine. But it&#8217;s a very special type of environment compared to other options in this space. <strong>Node.js is completely asynchronous.</strong> This means that everything you do in Node.js, you do in terms of asynchronous-friendly API&#8217;s, like network calls, file i/o, etc.</p>
<p>But even more important is that Node.js is specially designed to operate as an independent and fully-functional network server. What do I mean by this? Node.js&#8217; flagship capability, and indeed how most people use it, is its ability to &#8220;listen&#8221; for incoming requests on a particular network port (like port 80 for web traffic) and service those requests like a web server like Apache or IIS might do. <strong>In other words, Node.js at its most optimal is a drop-in replacement for your current web server.</strong> And it wraps in a fully capable application server (using JavaScript) automatically. Cool, huh?!</p>
<p>Because Node.js is asynchronous, it doesn&#8217;t operate under the covers at all like other web servers do. Instead, it operates in an &#8220;evented processing loop&#8221; where it is simultaneously and asynchronously listening for incoming connections, firing off processing to handle each connection, and then &#8220;listening&#8221; for those processing contexts to finish to hand the results back to the requesting connection stream. The result is that in many use-cases, Node.js is able to achieve mind-blowing amounts of parallel processing and throughput compared to more standard web servers like Apache.</p>
<p>Bottom line: Node.js&#8217; core competency is to take a server-side JavaScript application server environment and wrap it cleanly around a super-efficient asynchronous network server. In most respects, this is simply the most efficient server-side JavaScript environment you&#8217;re likely to ever find, and it allows JavaScript to compete head-to-head with even optimized, compiled binary alternatives.</p>
<h4>Is it for me?</h4>
<p>Up until now, every thing I&#8217;ve spoken about and written regarding middle-end architecture and server-side JavaScript has been conspicuously silent on the topic of Node.js. There is good reason for that, but I only want to touch briefly on it here, by means of comparison. The next post will dive into this much more thoroughly.</p>
<p>The utter awesomeness that is Node.js comes with a <em>price</em>. For most developers who are hacking and tinkering with new ideas all the time, this price is mere &#8220;pocket change&#8221; and that&#8217;s probably the biggest reason why the Node.js community has grown so quickly and so broad. But there is a &#8220;silent majority&#8221; lurking out there for whom the Node.js price may not be quite so trivial. What is this <em>price</em>? Infrastructure.</p>
<p>Thus far, my focused efforts have been on finding the lowest possible barrier-of-entry into the server-side JavaScript world. By barrier-of-entry, I mean the least amount of footprint/impact on existing infrastructure/architecture and to existing maintenance and support/IT staff. The current fruits of that labor has been the humble <a href="http://github.com/getify/BikechainJS">BikechainJS</a> server-side JavaScript project. </p>
<p>I shyed away from presenting my middle-end ideas in the context of Node.js because there are many who cannot necessarily proceed under the guise of replacing their top-level web server (along with all its associated dependencies, modules, configurations, etc) with an entirely new (and fundamentally paradigm-shifting) solution like Node.js. No doubt we&#8217;d mostly all agree that it would be exciting and probably even more efficient, but the slow-to-change momentum of existing applications, teams, infrastructure, maintenance, reliability, and IT support staff have a noticeably chilling effect on the hyper-excited server-side JavaScript movement.</p>
<p>It was my goal that something like BikechainJS, with its synchronous, per-request paradigm, could squeeze much more nimbly into existing application infrastructure, even at the cost of the wins from Node.js&#8217; performance.</p>
<h4>But Node.js is just so damn awesome!</h4>
<p>That&#8217;s absolutely true. And I&#8217;ve come to believe that the awesomeness of Node.js does not <em>have</em> to be mutually exclusive of the middle-end architectural ideas I&#8217;m advocating for, nor does it <em>have</em> sit out of reach from so many existing web applications, dev teams, and web shops.</p>
<p><strong>Node.js <em>can</em> (and perhaps should!) be the magic key to unlocking the full potential of your application&#8217;s middle-end.</strong></p>
<p>What if we can have our cake and eat it, too? What if we can find a clean way to plug Node.js into the existing infrastructure of our web applications, and at the same time give it the power to revolutionize our middle-end tasks? We&#8217;d get exponentially better performance <em>and</em> revolutionary better code architecture. That idea is just so full of win it&#8217;s hard to type without going nuts!</p>
<h4>Augment, not replace</h4>
<p>My biggest mental sticking point all along with Node.js has been the (im)practicality of asking an existing application to just simply swap out its entire web server tier for Node.js. I explored even the idea of running Node.js in a more limited, synchronous, per-request (CGI-like) context, but quickly found that was like trying to teach a bird to swim.</p>
<p>Then it hit me. The best way Node.js revolutionizes the middle-end of your existing/legacy web application is if you build your middle-end Node.js-based and insert it wholly into the stack in between the browser and your existing server.</p>
<p>In this respect, your middle-end Node.js layer becomes a &#8220;proxy&#8221; (or &#8220;web balancer&#8221;) server of sorts, sitting in front of your existing web server. All you have to do is bring up a Node.js VM/server instance (even cloud-based!) and direct all your primary traffic to that instance first. Then, you build out your middle-end architecture, doing templating, URL routing, data validation, and all the other tasks, as necessary, in your Node.js server-side JavaScript, and finally, you hook Node.js up to ferrying requests back over to your existing application server.</p>
<p>In this blind-proxy model, you start off with a dumb pass-thru of all your application&#8217;s requests, and then one-by-one you can inject some intermediate middle-end logic using the server-side JavaScript. For instance, <a href="http://blog.getify.com/2010/07/how-to-begin-your-middle-end/">as I talked about before</a>, you can start doing data-validation of inbound data fields using your Node.js-driven JavaScript. And then you can move on to evolving your templating into a true middle-end task in your JavaScript. And so on.</p>
<h4>Win, win, win</h4>
<p>The benefits of this approach are hard to explain by mere words. First and foremost, you will see an insane jump in the request/response performance simply by letting Node.js manage your application&#8217;s front line web server handling. But equally important, you gain invaluable flexibility to start converting your thick back-end into a well-crafted middle-end/back-end approach. And you don&#8217;t have to change very much of your existing infrastructure at all.</p>
<p>This is what I like to call a &#8220;middle-win&#8221; scenario! Node.js really rocks the middle-end.</p>
<div><a class="addthis_button" href="//addthis.com/bookmark.php?v=250" addthis:url='http://blog.getify.com/why-node-js-rocks-the-middle-end/' addthis:title='Why Node.js rocks the middle-end '><img src="//cache.addthis.com/cachefly/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://blog.getify.com/why-node-js-rocks-the-middle-end/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Content Delivery Network via getiblog.2static.it

Served from: blog.getify.com @ 2012-02-22 17:49:01 -->
