<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Chris Wu's blog</title>
    <link href="http://chriswu.me/atom.xml" rel="self" />
    <link href="http://chriswu.me" />
    <id>http://chriswu.me/atom.xml</id>
    <author>
        <name>Chris Wu</name>
        <email>contact@chriswu.me</email>
    </author>
    <updated>2014-01-13T00:00:00Z</updated>
    <entry>
    <title>A LRU Cache in 10 Lines of Java</title>
    <link href="http://chriswu.me/blog/a-lru-cache-in-10-lines-of-java/" />
    <id>http://chriswu.me/blog/a-lru-cache-in-10-lines-of-java/</id>
    <published>2014-01-13T00:00:00Z</published>
    <updated>2014-01-13T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>A LRU Cache in 10 Lines of Java</h1>
    <span class="date">January 13, 2014</span>
  </header>

  <section>
    <p>I had a couple of interviews long ago which asked me to implemented a <a href="http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used">last recently used (LRU)</a> cache. A cache itself can simply be implemented using a hash table, however adding a size limit gives an interesting twist on the question. Let’s take a look at how we can do this.</p>
<h2 id="last-recently-used-cache-eviction">Last Recently Used Cache Eviction</h2>
<p>To accomplish cache eviction we need to be easily able to:</p>
<ul>
<li>query the last recently used item</li>
<li>mark an item as the most recently used item</li>
</ul>
<p>A linked list allows for both operations. Checking for the least recently used item can just return the tail. Marking an item as recently used can be simply removing it from its current position and moving it to the head. The missing puzzle piece is finding this item in the linked list quickly.</p>
<h2 id="hash-tables-to-the-rescue">Hash tables to the rescue</h2>
<p>Looking into our data structure toolbox, hash tables allow us to easily index an object in (amortized) constant time. If we create a hash table from <code>key -&gt; list node</code>, we can find the most recently used node in constant time. The converse is true in that we can also still check for the existence (or lack-there-of) in constant time as well.</p>
<p>After looking up the node we can then move it to the front of the linked list to mark it as the most recently used item.</p>
<h2 id="the-java-shortcut">The Java shortcut</h2>
<p>Sometimes knowing less common data structures from the standard library of various programming languages can prove to be of help. Given this hybrid data structure we would have to implement a hash table on top of a linked list. However Java already provides this for us in the form of a <code>LinkedHashMap</code>! It even provides an overridable eviction policy method (<code>removeEldestEntry</code> <a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#removeEldestEntry(java.util.Map.Entry)">docs</a>). The only catch is that by default the linked list order is the insertion order, not access. However one of the constructor exposes an option use the access order instead (<a href="http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html#LinkedHashMap(int,%20float,%20boolean)">docs</a>).</p>
<p>Without further ado:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">import java.util.LinkedHashMap;</span>
<span class="kw">import java.util.Map;</span>

<span class="kw">public</span> LRUCache&lt;K, V&gt; <span class="kw">extends</span> LinkedHashMap&lt;K, V&gt; {
  <span class="kw">private</span> <span class="dt">int</span> cacheSize;

  <span class="kw">public</span> <span class="fu">LRUCache</span>(<span class="dt">int</span> cacheSize) {
    <span class="kw">super</span>(<span class="dv">16</span>, <span class="fl">0.75</span>, <span class="kw">true</span>);
    <span class="kw">this</span>.<span class="fu">cacheSize</span> = cacheSize;
  }

  <span class="kw">protected</span> <span class="dt">boolean</span> <span class="fu">removeEldestEntry</span>(Map.<span class="fu">Entry</span>&lt;K, V&gt; eldest) {
    <span class="kw">return</span> <span class="fu">size</span>() &gt;= cacheSize;
  }
}</code></pre>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>
<entry>
    <title>Getting Request URI and Content in C++ FCGI</title>
    <link href="http://chriswu.me/blog/getting-request-uri-and-content-in-c-plus-plus-fcgi/" />
    <id>http://chriswu.me/blog/getting-request-uri-and-content-in-c-plus-plus-fcgi/</id>
    <published>2012-03-24T00:00:00Z</published>
    <updated>2012-03-24T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>Getting Request URI and Content in C++ FCGI</h1>
    <span class="date">March 24, 2012</span>
  </header>

  <section>
    <p><a href="http://chriswu.me/blog/writing-hello-world-in-fcgi-with-c-plus-plus">Previously I had mentioned</a> how to create a simple hello world application in c++ with fcgi. However this simple application doesn’t allow for any inputs. This post we’ll show how retrieve the request uri accessed as well as the POST body content.</p>
<h2 id="getting-the-uri-and-post-content">Getting the URI and POST content</h2>
<p>Looking at the previous app, the output was a very simple hello, world. We will add functionality which spits back out the path that we hit the server with. Our desired functionality looks like:</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="kw">&gt;</span> <span class="kw">curl</span> -d <span class="st">&quot;Chris&quot;</span> http://localhost/foobar
<span class="kw">&lt;html&gt;</span>
  <span class="kw">&lt;head&gt;</span>
    <span class="kw">&lt;title&gt;</span>Hello, world!<span class="kw">&lt;</span>/title<span class="kw">&gt;</span>
  <span class="kw">&lt;</span>/<span class="kw">head&gt;</span>
  <span class="kw">&lt;body&gt;</span>
    <span class="kw">&lt;h1&gt;</span>Hello Chris from /foobar !<span class="kw">&lt;</span>/h<span class="kw">1&gt;</span>
  <span class="kw">&lt;</span>/<span class="kw">body&gt;</span>
<span class="kw">&lt;</span>/<span class="kw">html&gt;</span></code></pre>
<p>Notice that we respond with <code>Hello &lt;post content&gt; from &lt;request uri&gt;</code>. In order to do this we will have to capture the request uri and the post content. Let’s start off with the easier one which is the request uri. The request uri is buried within the <code>FCGX_Request</code>’s environment parameters. We can extract it using the <code>FCGX_GetParam</code> function like so:</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp"><span class="dt">const</span> <span class="dt">char</span> * uri = FCGX_GetParam(<span class="st">&quot;REQUEST_URI&quot;</span>, request.envp);</code></pre>
<p>Note how we get the param ‘REQUEST_URI’ as named in our nginx configuration.</p>
<p>The slightly trickier part is getting the request content. We will write a helper function to do this for us. We start by determining the <code>CONTENT_LENGTH</code> of the response. If missing we assume it to be 0 since it is not safe to read from the fcgi request if it is missing. We limit the content length to ensure we don’t run out of memory and set it to an arbitrary high value (<code>STDIN_MAX</code>). If we can’t parse the content length we will just assume the max number of bytes.</p>
<p>This starts the function off with:</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp">string get_request_content(<span class="dt">const</span> FCGX_Request &amp; request) {
    <span class="dt">char</span> * content_length_str = FCGX_GetParam(<span class="st">&quot;CONTENT_LENGTH&quot;</span>,
                                               request.envp);
    <span class="dt">unsigned</span> <span class="dt">long</span> content_length = STDIN_MAX;

    <span class="kw">if</span> (content_length_str) {
        content_length = strtol(content_length_str,
                                &amp;content_length_str,
                                <span class="dv">10</span>);

        <span class="kw">if</span> (*content_length_str) {
            cerr &lt;&lt; <span class="st">&quot;Can&#39;t Parse &#39;CONTENT_LENGTH=&#39;&quot;</span>
                 &lt;&lt; FCGX_GetParam(<span class="st">&quot;CONTENT_LENGTH&quot;</span>, request.envp)
                 &lt;&lt; <span class="st">&quot;&#39;. Consuming stdin up to &quot;</span> &lt;&lt; STDIN_MAX &lt;&lt; endl;
        }

        <span class="kw">if</span> (content_length &gt; STDIN_MAX) {
            content_length = STDIN_MAX;
        }
    } <span class="kw">else</span> {
        <span class="co">// Do not read from stdin if CONTENT_LENGTH is missing</span>
        content_length = <span class="dv">0</span>;
    }
    ...
}</code></pre>
<p>Now we have the content length we may actually read from standard input, up to the content_length number of characters.</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp">...
    <span class="dt">char</span> * content_buffer = <span class="kw">new</span> <span class="dt">char</span>[content_length];
    cin.read(content_buffer, content_length);
    content_length = cin.gcount();
...</code></pre>
<p>As a caveat of mod_fastcgi (currently not being used but nevertheless it can’t hurt to be a bit defensive) is that we need to consume the rest of stdin for the request because it doesn’t handle the request correctly otherwise.</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp">...
    <span class="co">// ignore() doesn&#39;t set the eof bit in some versions of glibc++</span>
    <span class="co">// so use gcount() instead of eof()...</span>
    <span class="kw">do</span> cin.ignore(<span class="dv">1024</span>); <span class="kw">while</span> (cin.gcount() == <span class="dv">1024</span>);
...</code></pre>
<p>Finally we can package up the content into a string and free the allocated memory for our content_buffer.</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp">...
    string content(content_buffer, content_length);
    <span class="kw">delete</span> [] content_buffer;
    <span class="kw">return</span> content;
}</code></pre>
<h2 id="end-result">End Result</h2>
<p>Adding some simple changes to call this function and get the uri we end up with a fcgi program that takes http input! <a href="/code/hello_world_fcgi/main_v2.cpp">Download final version here (main_v2.cpp)</a></p>
<p>To run this code we recompile with main_v2.cpp and spawn the fcgi process again (<a href="/blog/writing-hello-world-in-fcgi-with-c-plus-plus#running-the-code">link</a>).</p>
<p>If we use curl to post to the site we get:</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="kw">&gt;</span> <span class="kw">curl</span> -d <span class="st">&quot;chris&quot;</span> http://localhost/foobar
<span class="kw">&lt;html&gt;</span>
  <span class="kw">&lt;head&gt;</span>
    <span class="kw">&lt;title&gt;</span>Hello, World!<span class="kw">&lt;</span>/title<span class="kw">&gt;</span>
  <span class="kw">&lt;</span>/<span class="kw">head&gt;</span>
  <span class="kw">&lt;body&gt;</span>
    <span class="kw">&lt;h1&gt;</span>Hello chris from /foobar !<span class="kw">&lt;</span>/h<span class="kw">1&gt;</span>
  <span class="kw">&lt;</span>/<span class="kw">body&gt;</span>
<span class="kw">&lt;</span>/<span class="kw">html&gt;</span></code></pre>
<p>And a simple fcgi app in c++ is done!</p>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>
<entry>
    <title>Writing Hello World in FCGI with C++</title>
    <link href="http://chriswu.me/blog/writing-hello-world-in-fcgi-with-c-plus-plus/" />
    <id>http://chriswu.me/blog/writing-hello-world-in-fcgi-with-c-plus-plus/</id>
    <published>2012-03-23T00:00:00Z</published>
    <updated>2012-03-23T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>Writing Hello World in FCGI with C++</h1>
    <span class="date">March 23, 2012</span>
  </header>

  <section>
    <h2 id="prerequisites">Prerequisites</h2>
<p>This post will assume some familiarity with C++. The setup instructions also assume the server to deploy to is Ubuntu. This tutorial can be applied to other operating systems but I do not provide instructions on installing libraries on other operating systems.</p>
<h2 id="why-fcgi">Why FCGI?</h2>
<p><a href="http://en.wikipedia.org/wiki/FastCGI">FCGI (FastCGI)</a> is a protocol in which web applications can talk to a web server to serve web requests. Long story short FCGI was developed to solve the scalability shortcomings that CGI. Typical CGI applications will fork a new process to deal with the request. While this is convenient, it is terribly inefficient due to the overhead of creating and terminating a process for each web request. The idea with FCGI is that you can spawn a static number of processes to handle web requests. This allows for the overhead of creating and terminating processes to be eliminated as resources for request handling can be reused within one process handling multiple requests.</p>
<p>FCGI easily allows for our application to accept web requests by interacting with stdio. There are alternatives such as implementing your own http server using tools like <a href="http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/examples.html">boost</a>. Simple interface and robust are two of the key points of using fcgi for developing web applications in C++.</p>
<p>There are more reasons to use fcgi but you can check out the <a href="http://www.fastcgi.com/">official site</a> and the <a href="http://en.wikipedia.org/wiki/FastCGI">wikipedia page</a> for more info.</p>
<h2 id="installation">Installation</h2>
<p>We will need to install the libfcgi++ library, a web server (nignx in our case) and spawn-fcgi to run the fcgi app. We’ll also install curl to help test later on.</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="kw">sudo</span> apt-get install libfcgi-dev
<span class="kw">sudo</span> apt-get install spawn-fcgi
<span class="kw">sudo</span> apt-get install nginx
<span class="kw">sudo</span> apt-get install curl</code></pre>
<h2 id="the-code">The Code</h2>
<p>Most of this code is basically a copy paste re-interpretation of the example <a href="http://www.fastcgi.com/devkit/examples/echo-cpp.cpp">echo-cpp.cpp</a> from fastcgi.com</p>
<pre class="sourceCode cpp"><code class="sourceCode cpp"><span class="ot">#include &lt;iostream&gt;</span>
<span class="ot">#include &quot;fcgio.h&quot;</span>

<span class="kw">using</span> <span class="kw">namespace</span> std;

<span class="dt">int</span> main(<span class="dt">void</span>) {
    <span class="co">// Backup the stdio streambufs</span>
    streambuf * cin_streambuf  = cin.rdbuf();
    streambuf * cout_streambuf = cout.rdbuf();
    streambuf * cerr_streambuf = cerr.rdbuf();

    FCGX_Request request;

    FCGX_Init();
    FCGX_InitRequest(&amp;request, <span class="dv">0</span>, <span class="dv">0</span>);

    <span class="kw">while</span> (FCGX_Accept_r(&amp;request) == <span class="dv">0</span>) {
        fcgi_streambuf cin_fcgi_streambuf(request.in);
        fcgi_streambuf cout_fcgi_streambuf(request.out);
        fcgi_streambuf cerr_fcgi_streambuf(request.err);

        cin.rdbuf(&amp;cin_fcgi_streambuf);
        cout.rdbuf(&amp;cout_fcgi_streambuf);
        cerr.rdbuf(&amp;cerr_fcgi_streambuf);

        cout &lt;&lt; <span class="st">&quot;Content-type: text/html</span><span class="ch">\r\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;</span><span class="ch">\r\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;&lt;html&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;  &lt;head&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;    &lt;title&gt;Hello, World!&lt;/title&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;  &lt;/head&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;  &lt;body&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;    &lt;h1&gt;Hello, World!&lt;/h1&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;  &lt;/body&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>
             &lt;&lt; <span class="st">&quot;&lt;/html&gt;</span><span class="ch">\n</span><span class="st">&quot;</span>;

        <span class="co">// Note: the fcgi_streambuf destructor will auto flush</span>
    }

    <span class="co">// restore stdio streambufs</span>
    cin.rdbuf(cin_streambuf);
    cout.rdbuf(cout_streambuf);
    cerr.rdbuf(cerr_streambuf);

    <span class="kw">return</span> <span class="dv">0</span>;
}</code></pre>
<p>Breaking code dump down we see that the de-facto interface to stdio (cout/cin/cerr) are hijacked to serve the purposes of request handling. It’s possible to retrieve the iostreams back since we save the stdio stream buffers.</p>
<p>We then initialize the FCGX library with <code>FCGX_Init()</code> and initialize the request object that we share across requests for the lifetime of this process.</p>
<p>We then have a blocking loop accepting fcgi requests with our call to <code>FCGX_Accept_r</code>. The <code>_r</code> version calls the multi-thread safe version of the function, although this is not necessary in our single threaded program. This will cleanup the old request that was passed into <code>FCXG_Accept_r</code> and initialize the new request when it comes in.</p>
<p>We construct the fcgi stream buffers inside the loop, using <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization">RAII</a> pattern to ensure the buffers are flushed at the end of the request processing (end of the loop)</p>
<h2 id="nginx-config">Nginx Config</h2>
<p>Next up we’ll setup nginx to listen on port 80 for http requests and forward those along the the fcgi process which will listen on port 8000.</p>
<p>The key directive is <code>fastcgi_pass 127.0.0.1:8000</code> indicates that nginx should forward the fcgi request to port 8000 at localhost. You can replace the address with an <a href="http://wiki.nginx.org/HttpUpstreamModule">upstream directive</a> if you want to want to load balance across many processes. The rest of the <code>fastcgi_param</code> directives are optional and just set appropriate environment variables which get forwarded to the fcgi application.</p>
<pre class="sourceCode ini"><code class="sourceCode ini"><span class="dt">events {</span>
<span class="dt">  worker_connections 1024;</span>
<span class="dt">}</span>

<span class="dt">http {</span>
<span class="dt">  server {</span>
<span class="dt">    listen 80;</span>
<span class="dt">    server_name localhost;</span>

<span class="dt">    location / {</span>
<span class="dt">      fastcgi_pass   127.0.0.1:8000;</span>

<span class="dt">      fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;</span>
<span class="dt">      fastcgi_param  SERVER_SOFTWARE    nginx;</span>
<span class="dt">      fastcgi_param  QUERY_STRING       $query_string;</span>
<span class="dt">      fastcgi_param  REQUEST_METHOD     $request_method;</span>
<span class="dt">      fastcgi_param  CONTENT_TYPE       $content_type;</span>
<span class="dt">      fastcgi_param  CONTENT_LENGTH     $content_length;</span>
<span class="dt">      fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;</span>
<span class="dt">      fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;</span>
<span class="dt">      fastcgi_param  REQUEST_URI        $request_uri;</span>
<span class="dt">      fastcgi_param  DOCUMENT_URI       $document_uri;</span>
<span class="dt">      fastcgi_param  DOCUMENT_ROOT      $document_root;</span>
<span class="dt">      fastcgi_param  SERVER_PROTOCOL    $server_protocol;</span>
<span class="dt">      fastcgi_param  REMOTE_ADDR        $remote_addr;</span>
<span class="dt">      fastcgi_param  REMOTE_PORT        $remote_port;</span>
<span class="dt">      fastcgi_param  SERVER_ADDR        $server_addr;</span>
<span class="dt">      fastcgi_param  SERVER_PORT        $server_port;</span>
<span class="dt">      fastcgi_param  SERVER_NAME        $server_name;</span>
<span class="dt">    }</span>
<span class="dt">  }</span>
<span class="dt">}</span></code></pre>
<h2 id="running-the-code">Running the code</h2>
<p>The system now comprises of three parts. One will be the executable fcgi c++ app. In order to run this we need spawn-fcgi and to listen to a port. Nginx will then forward web requests to this port, translating the http proctocol into the fast cgi protocol.</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="co"># run nginx using the provided configuration</span>
<span class="kw">sudo</span> nginx -c <span class="kw">&lt;</span>path to nginx.conf<span class="kw">&gt;</span>

<span class="co"># compile hello_world</span>
<span class="kw">g++</span> main_v1.cpp -lfcgi++ -lfcgi -o hello_world

<span class="co"># spawn the fcgi app on port 8000 with no fork</span>
<span class="kw">spawn-fcgi</span> -p 8000 -n hello_world</code></pre>
<p>Then just head to the browser and enter <a href="http://localhost/" class="uri">http://localhost/</a> into the location bar and voilà! Hello, World! See the <a href="/blog/getting-request-uri-and-content-in-c-plus-plus-fcgi">next part</a> in this tutorial to see how to incorporate the request uri and the request content into this simple app.</p>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>
<entry>
    <title>C++ for the Real-Time Web</title>
    <link href="http://chriswu.me/blog/cpp-for-the-real-time-web/" />
    <id>http://chriswu.me/blog/cpp-for-the-real-time-web/</id>
    <published>2012-01-29T00:00:00Z</published>
    <updated>2012-01-29T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>C++ for the Real-Time Web</h1>
    <span class="date">January 29, 2012</span>
  </header>

  <section>
    <h2 id="c-why-on-earth">C++? Why on Earth?</h2>
<p>C++ seems like one of the least likely languages to write a web application in. C++ is associated with complexity, both with language design and the need to manually manage memory. Programming in C++ unleashes a whole class of bugs associated with memory corruption and memory allocation. This is a trade off for giving more power to the developer along generally being much faster than equivalent programs in languages such as Python or Ruby.</p>
<h2 id="real-time-web-as-a-use-case">Real-time Web as a Use Case</h2>
<p>Making a hard real-time application<a href="#fn1" class="footnoteRef" id="fnref1"><sup>1</sup></a> on the web is a futile task. Unpredictable network latencies make this an impossible task. However firm real-time systems are possible<a href="#fn2" class="footnoteRef" id="fnref2"><sup>2</sup></a>. This means that our application can miss a few deadlines without a total system failure.</p>
<p>Deterministic timing is key when designing real-time systems. Systems do not have to be necessarily high performance as long as deadlines are met. Lack of a garbage collector ensures there are no “pauses” in the execution of the application while the garbage collector runs to reclaim unused memory. This is not to say that it is not possible to create real-time applications in managed languages<a href="#fn3" class="footnoteRef" id="fnref3"><sup>3</sup></a> but C++ has the advantage of not needing to worry about garbage collection freezing the program.</p>
<p>When might such an application come up? One instance might be if we have a web service that “guarantees”<a href="#fn4" class="footnoteRef" id="fnref4"><sup>4</sup></a> a response time. These types of services are typically internal services.</p>
<h2 id="real-time-bidders">Real-Time Bidders</h2>
<p>A good example of an external facing application that has a firm real-time requirement are <a href="http://en.wikipedia.org/wiki/Real_Time_Bidding">real-time bidders</a>. These servers bid on ads from ad exchanges which act as an auction house for ad real-estate on the web. Each request represents a potential ad placement. Real-time bidders (RTB) typically must respond within a set deadline (including network transfer time). For example an auction server from <a href="http://www.openx.com/advertiser/real-time-bidding">OpenX</a> must receive the complete response from a RTB within 125ms. RTBs which violate this deadline repeatedly will have less chances to bid on future auctions, reducing the effectiveness of the RTB. This presents a firm real-time problem because:</p>
<ul>
<li>failure to meet the deadline is acceptable but quality of service is degraded – not hard real-time</li>
<li>after the deadline the result (bid response) is worthless – not soft real-time</li>
</ul>
<h2 id="side-note-about-scheduling-or-lack-thereof">Side Note About Scheduling (or Lack Thereof)</h2>
<p>One topic that hasn’t been covered is scheduling. Assuming the web application is running on a typical flavour of Linux, there is no sense of a real-time scheduler. Depending on the strictness of the real-time constraints it may or may not be necessary to modify the scheduling behaviour of the kernel. Since web application are usually the only main processes living on a single server (or at least a highly dominant one), modifications to scheduling may not be worth the effort versus setting a high priority on the real-time process. These are trade offs I have not run into yet because they usually are only needed under very tight and/or strict real-time deadlines.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Hard real-time meaning a missed deadline is a total system failure.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>A firm real-time system is a system where some failures are tolerable but the result of the computation is useless after the deadline has passed.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Many real-time high frequency trading programs are done in managed languages in C# and Java.<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>Guarantee in the loose sense that it has a deadline for the firm real-time system.<a href="#fnref4">↩</a></p></li>
</ol>
</div>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>
<entry>
    <title>First Contribution to Open Source</title>
    <link href="http://chriswu.me/blog/first-contribution-to-open-source/" />
    <id>http://chriswu.me/blog/first-contribution-to-open-source/</id>
    <published>2011-08-10T00:00:00Z</published>
    <updated>2011-08-10T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>First Contribution to Open Source</h1>
    <span class="date">August 10, 2011</span>
  </header>

  <section>
    <p>Most of the apps I’ve built stand on the shoulder of giants. Open source projects enabled me to jump ahead of building frameworks or webservers and dive straight into building the end product. I’ve always been thankful and felt a need to give back, even in a small way. Recently (while procrastinating from exams) I’ve finally <a
href="http://github.com/visionmedia/connect-redis/pull/28">done such a thing</a>.</p>
<p>I’ve recently been working on a flash card-esque site for learning <a href="http://en.wikipedia.org/wiki/Kana" title="Kana">kana</a>. Using redis as the backend I proceeded to use <a href="http://github.com/visionmedia/connect-redis">connect-redis</a> to implement sessions. Unfortunately this cluttered my app’s data keyspace with session data with no clear way of being able to separate the two.</p>
<p>Luckily enough for me redis has multiple databases to store data in separate keyspaces. All you had to do was run a <code>select &lt;db num&gt;</code> command. connect-redis even foresaw this issue and has a <code>db</code> option in the <code>RedisStore</code> constructor.</p>
<h2 id="the-ugly-bug">The Ugly ‘Bug’</h2>
<p>After running the server for a while I would notice a peculiar bug. It seemed my session data kept resetting after a day or two. Inspecting the redis db I saw that my app data’s database suddenly had session data in it even though I told the <code>RedisStore</code> to use the session db.</p>
<p>Digging around I found that the <a href="http://github.com/mranney/node_redis">node redis</a> client <a href="http://github.com/mranney/node_redis/issues/86">doesn’t reselect db’s on reconnection</a>. What was happening was the redis client connection was dropping randomly overnight but was able to re-connect. Good recovery, except now it’s connected to the default db 0 as per the select command <a href="http://redis.io/commands/select">docs</a>. <em>Fun stuff</em>.</p>
<h2 id="working-around-it">Working Around It</h2>
<p>Since the issue didn’t seem conclusive at the time and this was affecting connect-redis I thought to patch it up with the following code taken from the discussion of <a href="http://github.com/mranney/node_redis/issues/86">issue 86</a> of <a href="http://github.com/mranney/node_redis">node redis</a>.</p>
<pre class="js"><code>client.on(&quot;connect&quot;, function() {
  client.send_anyway = true;
  client.select(db);
  client.send_anyway = false;
});</code></pre>
<p>Ugly? Yes. Necessary? Unfortunately also Yes.</p>
<p>The <code>client.send_anyway</code> dictates whether commands should be enqueued onto the offline queue when the client has not connected. Since we want to select the proper db <strong>before</strong> the offline queue is executed the <code>send_anyway</code> needs to be set <code>true</code> when issuing the select command.</p>
<p>I added this to my existing redis connections which used other databases and patched it to connect-redis in this <a href="http://github.com/visionmedia/connect-redis/pull/28">pull request</a>. It was picked up by <a href="http://github.com/visionmedia">visionmedia</a> in no time (like 2 minutes!) and merged into connect-redis for <a href="https://github.com/visionmedia/connect-redis/commit/c005be8a10a97a46d34cbd28eb61ffe82eb9c177">v1.0.7</a>.</p>
<h2 id="thoughts-and-more-ramblings">Thoughts and More Ramblings</h2>
<p>It was quite satisfying contributing to this library even if though I did almost no work of my own. Although this was a quick patch to ensure the connect-redis always used the db it was passed, a cleaner solution stemming within node redis would be best. Maybe I’ll take my time and invest in providing such an option in the future.</p>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>
<entry>
    <title>Hello World</title>
    <link href="http://chriswu.me/blog/hello-world/" />
    <id>http://chriswu.me/blog/hello-world/</id>
    <published>2011-05-18T00:00:00Z</published>
    <updated>2011-05-18T00:00:00Z</updated>
    <summary type="html"><![CDATA[<article>
  <header>
    <h1>Hello World</h1>
    <span class="date">May 18, 2011</span>
  </header>

  <section>
    <p>Finally setup a blog. I’ve always wanted to ramble nonsensically on my very own blog but never found the time to roll one out. Most people run the Wordpress route (or Tumblr these days), but I never really dug into Wordpress. It always seem bloated to me and I just wanted something simpler (and editable in vim). In comes <a href="http://jekyllrb.com/">Jekyll</a>!</p>
<p>Jekyll is a blog aware static site generator. Paired with <a href="http://pages.github.com/" title="Github Pages">github pages</a>, I was set. Github pages has the nice fact that it already supports jekyll site generation on a (specially named) repo push.</p>
<p>The only caveat to using Github Pages is that you can’t really run plugins like haml and sass converters. Jekyll is run with <code>jekyll --safe</code> which <a href="http://github.com/mojombo/jekyll/issues/277#issuecomment-1207974" title="Jekyll Plugin Issue">prevents haml and sass from running</a>.</p>
<p>Still on the todo list:</p>
<ul>
<li>Comments (disqus)</li>
<li>Search (tapir)</li>
<li>Prettify (I find this very difficult)</li>
<li>Get a Logo and Icon</li>
<li>Post something real</li>
</ul>
  </section>

  <hr />

  <p>
    <a href='#' id='load-comments'>Click to load comments</a>
  </p>
  <div id="disqus_thread"></div>
  <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>

</article>
]]></summary>
</entry>

</feed>
