<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ryan Irwin on Medium]]></title>
        <description><![CDATA[Stories by Ryan Irwin on Medium]]></description>
        <link>https://medium.com/@ryanirwin-2529?source=rss-e261d7f133be------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*r4NwPKaMKXZakanm.</url>
            <title>Stories by Ryan Irwin on Medium</title>
            <link>https://medium.com/@ryanirwin-2529?source=rss-e261d7f133be------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:47:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ryanirwin-2529/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Family Trip to Tahoe]]></title>
            <link>https://medium.com/ryaneirwin/family-trip-to-tahoe-bede0a292ada?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/bede0a292ada</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 01:54:13 GMT</pubDate>
            <atom:updated>2021-02-20T02:18:47.533Z</atom:updated>
            <content:encoded><![CDATA[<p>This is post about our trip to Tahoe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bede0a292ada" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ryaneirwin/family-trip-to-tahoe-bede0a292ada">Family Trip to Tahoe</a> was originally published in <a href="https://medium.com/ryaneirwin">ryaneirwin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Family]]></title>
            <link>https://medium.com/ryaneirwin/family-e3ebaf020c7f?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ebaf020c7f</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 01:37:57 GMT</pubDate>
            <atom:updated>2021-04-23T13:41:52.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Family blog post</p><p>Edit — adding to the story</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ebaf020c7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ryaneirwin/family-e3ebaf020c7f">Family</a> was originally published in <a href="https://medium.com/ryaneirwin">ryaneirwin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running]]></title>
            <link>https://medium.com/ryaneirwin/running-d1345cf51466?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1345cf51466</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 20 Feb 2021 01:35:57 GMT</pubDate>
            <atom:updated>2021-02-20T01:35:57.069Z</atom:updated>
            <content:encoded><![CDATA[<p>Running is important to me. Period.</p><p>(test post)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1345cf51466" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ryaneirwin/running-d1345cf51466">Running</a> was originally published in <a href="https://medium.com/ryaneirwin">ryaneirwin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Day in the Life of a Data Engineer]]></title>
            <link>https://medium.com/insight-data/a-day-in-the-life-of-a-data-engineer-35efacaa6b2e?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/35efacaa6b2e</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[insight-data-engineering]]></category>
            <category><![CDATA[yelp]]></category>
            <category><![CDATA[infrastructure]]></category>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Fri, 28 Oct 2016 00:33:00 GMT</pubDate>
            <atom:updated>2016-10-28T00:33:00.657Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ryan Irwin, Yelp</h4><p><strong><em>Ryan Irwin is a Software Engineer (Data Infrastructure) at Yelp. Prior to joining Yelp, he was a </em></strong><a href="http://insightdataengineering.com/?utm_source=ryanday&amp;utm_medium=blog"><strong><em>Data Engineering Fellow at Insight</em></strong></a><strong><em>. This post is part of our </em></strong><a href="https://blog.insightdatascience.com/introducing-a-day-in-the-life-of-a-data-engineer-blog-series-31f12e49af8e"><strong><em>Day in the Life of Data series</em></strong></a><strong><em>, where </em></strong><a href="http://insightdataengineering.com/fellows?utm_source=ryanday&amp;utm_medium=blog"><strong><em>our alumni</em></strong></a><strong><em> discuss the daily challenges they work on at over 200 companies.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*aAg7I3HqamN4CZtod_a1cw.jpeg" /></figure><p>I’m hoping to share a glimpse of what it means to me to be a data engineer at Yelp, with responsibilities over data streams covering vastly different applications in a day-in-the-life blog post. Much of this post is from the perspective of an engineer on a growing team, with emphasis on <strong>team </strong>because improving our team’s systems would not be possible without the team. Specific technologies are only mentioned to provide additional context, and specific applications and features are largely omitted because general themes emerge.</p><h3>Team Responsibilities</h3><p>First, responsibilities. My team is responsible for outputting a daily log of valid traffic identifiers for other teams to consume in order to produce their own metrics. This means we ingest several logs in a <a href="https://en.wikipedia.org/wiki/MapReduce">MapReduce</a> job, and produce new logs to load into <a href="https://aws.amazon.com/redshift/">Redshift</a>. We are responsible for feature engineering and data-mining of the data in the logs, in addition to operational responsibilities to ensure that the job finishes on time.</p><p>Also, our team is responsible for a couple of real-time applications and services that perform <a href="https://kafka.apache.org/">Kafka</a> tailing on a subset of logs we consume in MapReduce, and provide a subset of filtering in real-time. Another requirement is for parts of the system to be interoperable with “humans in the loop” who seek to apply manual filtering when necessary. This sounds like a <a href="https://en.wikipedia.org/wiki/Lambda_architecture">Lambda Architecture</a>, but is only so in spirit from a high level.</p><h3>Operating the Infrastructure</h3><p>With the context of these team responsibilities, here are the day-to-day concerns we worry about. <em>Is the infrastructure running properly? Is it delivering the data we intended? Is our infrastructure affecting others, with co-location of services or costing too much?</em></p><p>To address these items we have alerts in place with different tools covering different failure scenarios. As our team grew, we wrote down “debug and recover” runbooks that emerged as patterns, and when possible we automated parts of the recovery or better utilized our underlying robust service infra (shout out to <a href="https://github.com/Yelp/paasta">PaaSTA</a>).</p><p>Inevitably, new problems will arise. We’ve found that defense against this can be helped with thorough documentation of past failures and non-failure-related changes (i.e., descriptive tickets, code reviews). Also, it is key to know your organization’s tooling for seeking information. It’s been said by many folks at Yelp that “<em>a senior engineer doesn’t know all the answers, but they’ll know where to start looking”</em>.</p><h3>Data-based Alerting</h3><p>The fun part of being on my team as a data engineer is that we get to do challenging analytics. Now that the data has been refined by our MapReduce or streaming systems, we have many alerts that could trigger if anomalies exist. In our case, this could mean that a bug in our logging system is causing mis-classifications, potential abuse on the platform, or a new traffic flow related to new site features. Many of our alerts exist at the intersection of our team and other teams, so clear cross-team communication is required.</p><p>Given an alert, we look at our pre-built <a href="https://www.splunk.com/">Splunk</a> or home-grown dashboards that contain items that we often look for. If we can’t find the answer there, we’ll often look at our logs loaded into Redshift after different stages of aggregation (event and session level). Sometimes we’ll leverage iPython notebooks for visualization.</p><p>Once the root causes of the anomaly have been identified from our perspective, we evaluate what actions need to be taken. <em>Should we surface the issue to other teams for additional input? Should we make a fast code change?</em> If quick code changes are required, having clean coding and testing procedures is key.</p><h3>Planning for the Future</h3><p>The day-to-day stuff involves some critical thinking, but it really sets up a continuous discussion for planning for the future. And just like the day-to-day infrastructure operations and data-based alerts aspect, planning involves both of those areas.</p><p>We continually ask ourselves: <em>Does our current infrastructure meet our needs in the future? Does it scale as site visitors increase and new application features are released?</em> Often our data needs will drive our infrastructure needs; for example, we might discover the plausibility of a new signal by ingesting more sources of data.</p><p>Also, there is an endless stream of new external technologies and nomenclature to keep pace with. We can pilot a new superior alternative, or try it out in the next company hackathon. Within the organization there is always an evolution on best practices, maybe in security or simplifications in the service infrastructure. Lastly, our team must understand how the organization’s needs for our data evolves. Currently, many things are transitioning from daily batch to streaming.</p><p>Often our data needs will drive our infrastructure needs; for example, we might discover the plausibility of a new signal by ingesting more sources of data. We also might want to improve our label acquisition practices allowing us to more easily tune our precision and recall for our filters. Improved labeling helps us use more machine learned models as opposed to manually-tuned models.</p><p>To cap off this post, my favorite part of being a data engineer at Yelp is the wide variety of interesting problems from low-level infrastructure to high-level data-science, all while working with really enthusiastic and talented folks.</p><p><strong><em>Want to become a data engineer at top companies like Yelp?</em></strong><em>The </em><a href="http://insightdataengineering.com/?utm_source=ryanday&amp;utm_medium=blog"><em>Insight Data Engineering Fellows Program</em></a><em> is free 7-week professional training where you can build cutting edge big data platforms and transition to a career in data engineering at top teams like Facebook, Uber, Slack and Squarespace.</em></p><p><a href="http://insightdataengineering.com/?utm_source=ryanday&amp;utm_medium=blog"><strong><em>Learn more about the program</em></strong></a><strong><em> and </em></strong><a href="http://insightdataengineering.com/apply?utm_source=ryanday&amp;utm_medium=blog"><strong><em>apply today</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35efacaa6b2e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insight-data/a-day-in-the-life-of-a-data-engineer-35efacaa6b2e">A Day in the Life of a Data Engineer</a> was originally published in <a href="https://medium.com/insight-data">Insight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Python Developer Practices]]></title>
            <link>https://ryanirwin-2529.medium.com/simple-python-developer-practices-8459c55cafc7?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/8459c55cafc7</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 30 May 2015 15:01:30 GMT</pubDate>
            <atom:updated>2020-11-19T18:55:24.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7svXRpjHG1BS5jAIBDlag.png" /></figure><p>[This is a test blog post moving from wordpress to medium, it’s a really old post.]</p><p><em>I dedicate this post to </em><a href="http://insightdataengineering.com/"><em>Insight Data Engineering</em></a><em>. It’s a great program that brought me to California one year ago this week.</em></p><p>I’ve missed several months of blogging because of a new job, buying a condo, and finishing the move across the country. In this simple blog, I’ll share how I like to set up a Python project. There will be no holy wars on editors or my choice to focus on Python. Rather, this blog is the missing blog I was looking for when I was learning the best practices with software engineering in Python. Specifically, this blog walks through how I would set up a Python project as of mid-2015 with tools including virtualenv, tox, make, pytest, mock, and a basic code structure.</p><p><strong>Virtualenv</strong></p><p>Virtual environments are essential for developing in Python when non-native Python libraries are needed, like a MySQL client. Run the following command at the top-level of your repo to create a directory called virtualenv_run with the Python 2.7 interpreter inside.</p><pre>virtualenv virtualenv_run --python=python2.7</pre><p>To <em>enter</em> the new virtualenv, execute source virtualenv_run/bin/activate. I execute that command so often, I have a bash alias src for this and name all my virtualenvs the same. While <em>inside</em> the virtualenv, you can now install packages with pip and they will be installed in the virtualenv_run directory and not in a directory owned by root (so stop using sudo pip install <em>some_package</em>).</p><p>Next, three files need to be added at the top level of the repo: setup.py, requirements.txt, and requirements-dev.txt. These files specify metadata about your repo/project and what dependencies you need. The format of setup.py is shown below. Other arguments including description, author, author_email, and url can also be included.</p><pre>from setuptools import find_packages from setuptools import setup setup( name=&quot;MyProject&quot;, version=&quot;0.1&quot;, packages=find_packages(exclude=[&#39;tests&#39;]), setup_requires=[&#39;setuptools&#39;], install_requires=[ &quot;MySQL-python&quot; ], )</pre><p>In this example, the package MySQL-python is listed as a dependency with install_requires kwarg without a pinned down version. This will install the latest version of the package that is available. It is a common practice to include dependencies in setup.py (over requirements.txt) as much as possible if your project is a library. If your project is a standalone application, service, or something with a main, it is more common to include dependencies with pinned version numbers in requirements.txt. See this <a href="https://caremad.io/2013/07/setup-vs-requirement/">blog</a> for a more detailed explanation.</p><p>The requirements-dev.txt (shown below) is designed to include the tools needed for testing. I also include a link to install the requirements.txt file at the top. Later, I’ll show uses for each package in my adopted workflow.</p><pre>-r requirements.txt coverage ipdb ipython flake8 mock pytest</pre><pre>-e . MySQL-python==1.2.5</pre><p>To build a virtualenv with these files simply execute pip install -r requirements-dev.txt.</p><p><strong>Tox</strong></p><p>The last component before starting development is to set up tox, a virtualenv-based test automation tool. Tox will run all of your unit tests, check for code style issues, code test coverage, and even kick off acceptance/integration tests. I’ll cover the first three uses in this blog. Below is an example tox.ini file.</p><pre>[tox] envlist = py27 [testenv] deps = -rrequirements-dev.txt commands = coverage run --source=&lt;YOUR_PROJECT&gt;/,tests/ -m pytest --strict {posargs:tests} flake8 . [flake8] ignore = E125 max-line-length = 120 max-complexity = 10 exclude = .git,.tox,virtualenv_run</pre><p>With this tox configuration file, the command tox will know how to run your suite of tests. It automatically build a clean virtualenv in a directory called .tox. It runs all unit tests in the tests directory. It reports the code coverage with the coverage. Always shoot for 100% code coverage with your tests. Certain lines like running main can be excluded with a .coveragerc file. If main is excluded from coverage, I&#39;d strongly suggest main consisting of only an object creation and a single call to a method like run.</p><p><strong>Directory Structure</strong></p><p>Finally, let’s write some code! I’ll share my opinions about high-level structure of your repo. First, create a tests directory for all tests. It is not by chance or accident that I mention tests first; the test code is as important as the production code! Second, create a directory for all of your production code to live. This name can even be the same as the repo name if no other name seems more appealing.</p><p>The remaining parts of the directory structure requires a brief discussion about software engineering. Think about separating the functionalities needed for your use cases. You’ll probably have some core objects and some object containers along with logic for manipulations of those objects or containers. You’ll also have some end delivery system for your use case like handling web requests, document creation, or database inserts.</p><p>The most important thing is to separate the core objects/logic from the delivery system because it makes switching delivery systems easier, and it makes managing the code easier. At the very least create a directory called components as a sub-directory of your production code directory, and the other sub-directory can be named after the delivery system (i.e., webserver). Also, the directory structure of the tests directory should match the adopted directory structure of the production code, so your tests are easier to find.</p><p><strong>Pytest</strong></p><p>The last thing, I’d like to cover is how to use a test framework in Python. I’ll share some examples using pytest and mock as well as quick pointers leveraging breakpoints in iPython. Test files can be named test_ <em>module_to_be_tested</em>.py in the directory that mirrors the module directory in the production code. I opt for classes for my tests instead of individual functions in a module. Test classes are named starting with “Test” and test methods are prepended with “test_”.</p><pre>@pytest.fixture def some_name(self): return &quot;Bob&quot; @pytest.fixture def some_person(self, some_name): return Person(name=some_name) def test_person_has_right_name(self, some_person, some_name): assert some_person.name == some_name</pre><p>I strive for putting any hardcoded strings or integers at the top of each test class. This makes refactoring the test code or production code easier. In the above example, if we wanted to change the name property to be a namedtuple or name object for additional features, we would only need to change the some_name fixture!</p><pre>@pytest.fixture def data_processor(self): return DataProcessor() @pytest.fixture def fake_results(self): return [0, 2, 4, 6, 10] @pytest.yield_fixture def raw_results_patch( self, data_processor, fake_results ): with mock.patch.object( data_processor, &#39;get_raw_results&#39;, return_value=fake_results ) as mock_get_raw_results: yield mock_get_raw_results def test_data_processor_sums_correctly( self, data_processor, raw_results_patch, fake_results ): summed_results = data_processor.get_sum_of_results() assert summed_results == sum(fake_results)</pre><p>This is a nice way to mock out the raw results to test summing independently of result retrieval, and if the raw_results_patch yield fixture is not included as an argument to another test, the test will not mock out the get_raw_results call. See <a href="http://mock.readthedocs.org/en/latest/examples.html">mock examples</a> to see more examples on mocking, and <a href="https://pytest.org/latest/contents.html">pytest documentation</a> for more on pytest.</p><p>There is a lot of stuff in this post. I hope you enjoyed it and found it helpful! Feel free to share feedback, and thanks for reading!</p><p><em>Originally published at </em><a href="https://ryaneirwin.com/2015/05/30/python-developer-practices/"><em>http://ryaneirwin.com</em></a><em> on May 30, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8459c55cafc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineering: From Basic Prototype to Production]]></title>
            <link>https://ryanirwin-2529.medium.com/data-engineering-from-basic-prototype-to-production-a630941aa0fc?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/a630941aa0fc</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Tue, 23 Sep 2014 19:48:53 GMT</pubDate>
            <atom:updated>2020-11-21T04:52:47.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*rvm24vtHNWLmA_b-.jpg" /></figure><p>Designing a scalable production-worthy system is a huge challenge that requires a careful balance of developing extensible code that is fast enough for production and time-management of hitting milestones while avoiding pre-mature optimization and dirty hacks. Here the ways I like to think about developing a scalable system:</p><ol><li>Write prototype in a program. It’s important to get something working end-to-end for a sanity check.</li><li>Refactor prototype code into classes, parameterize where necessary, and write unit tests for each class (use test-driven development!). Refactoring should involve abstracting away things like DB connections and queries, and making things configurable</li><li>Re-test end-to-end functionality, and create integration tests. All of this test writing gives us confidence later when making any changes.</li></ol><p>At this point, you have some decent looking code and a nice test suite, but it is not obvious how to scale from here. You might spot some places where parallelize execution of your code could help. However, this can be tricky business with extending code designed not to have parallel execution, and testing/debugging can be difficult because of the exponential combinations of state that need to be right for the program to work. I prefer using what I’ll call a workflow framework.</p><p>Let’s define a workflow framework as a tool or set of tools that separate execution into multiple tasks computing simultaneously with finer grained control and visibility on each task. As an example, think about submitting a large number of small tasks to a job server, like <a href="http://gearmanhq.com/help/tutorials/Python/basic/">gearman</a> or publishing jobs to a queue using <a href="http://peter-hoffmann.com/2012/python-simple-queue-redis-queue.html">Redis</a>.</p><p>This greatly helps software development because each piece can be developed and tested individually with ease. Failures on production can be isolated to a task and restarted automatically. Also, this isolation enables using different tools and languages to be used for isolated tasks; imagine submitting tasks from user input from a web-layer in Python and have workers processing requests using a lower-level language like C for performance reasons.</p><p>Lastly, you will find that if you isolated your classes well and have a good test suite, it will not be too difficult to move logic between different frameworks. Much of the code can be moved to worker classes that listens to a job server (Gearman) or a Redis queue.</p><p>This blog provides a high-level methodology of going from rough prototype hitting a real use-case to a maintainable and scalable system on production.</p><p><em>Originally published at </em><a href="https://ryaneirwin.com/2014/09/23/data-engineering-the-python-way/"><em>http://ryaneirwin.com</em></a><em> on September 23, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a630941aa0fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cython Performance Case Study]]></title>
            <link>https://ryanirwin-2529.medium.com/cython-performance-case-study-31838e901251?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/31838e901251</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 19 Jul 2014 22:28:00 GMT</pubDate>
            <atom:updated>2020-11-21T04:54:22.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*QUybOvU4cAEi2Fs9.jpg" /></figure><p>I’ve been learning different programming languages since the early 2000s. It can be tempting to clutch onto a language and use it no matter what. There are advantages to mastering a single language on a personal level and company level. However, the disadvantages include:</p><p>(1) not using new languages and their inherent strengths,</p><p>(2) reliant on language support for new tools,</p><p>(3) your build and testing infrastructure are stuck in a language (I really like Makefiles because they work in all languages!),</p><p>(4) using multiple languages may guide your implementation to have clearly defined modules, and</p><p>(5) not learning new languages can limit us as programmers (see Nathan Marz’s <a href="http://nathanmarz.com/blog/interview-with-programmer-magazine.html">blog</a> that suggests learning new languages makes us better programmers).</p><p>I started programming with C and C++, but higher-level languages like Python are attractive in terms of code-density and readability, which in my experience greatly help maintainability. Many Java and C++ software engineers dismiss Python as a production-grade language because it is much slower and it is not strongly typed (Often times they dismiss each other as well :-D, but that’s another topic.).</p><p>I wanted to do a short case study on sorting unique numbers in linear time using bit vectors in each of these languages. I wanted to see how much slower Python would be compared to the strongly typed languages for bit manipulation, and as the title eludes, compare all these to Cython.</p><p>The precise question, sort a file of unique numbers and write out the numbers to a file in sorted order. I plan to use a bit vector of integer type, with the idea of setting a bit at the memory address corresponding to the number’s value. Once I have all the numbers represented with one bit, I can loop through each bit of the bit vector and print out the numbers in order.</p><p>For me it was natural to think about implementing this algorithm in C. Here is a link to the full <a href="https://github.com/rirwin/sandbox/blob/master/scratch/cython-scratch/sort_phonebook.c">32-bit based implementation</a>. The important snippets below:</p><pre>// bit vector uint32_t *bvp = (uint32_t*)malloc(bv_size*sizeof(uint32_t)); // clear bit vector for (idx = 0; idx &lt; bv_size; idx++) { bvp[idx] = 0; } ... // ---- reads file and sets bits in bit vector ---- while (fscanf(ifp, &quot;%d&quot;, ph_num) != EOF) { idx = *ph_num/32; // calc which int in bv to set bit = *ph_num % 32; // calc which bit in int to set comp_int = 1; comp_int&lt;&lt;=bit; *(bvp + idx) = (*(bvp + idx) | comp_int); // set bit } // ---- outputs sorted numbers in file ---- for (idx = 0; idx &lt; bv_size; idx++) { comp_int = 1; if (*(bvp + idx) &gt; 0) { // small optimization for (bit = 0; bit &lt; 32; bit++) { if (comp_int &amp; *(bvp + idx)) fprintf(ofp,&quot;%d\n&quot;,idx*32+bit); comp_int&lt;&lt;=1; } } }</pre><p>Then, I wrote this in Python. I had never cared deeply about an integer’s bit length before in Python, so my first attempt was to use NumPy’s number types. Here is a link to the full <a href="https://github.com/rirwin/sandbox/blob/master/scratch/cython-scratch/sort_phonebook_python.py">Python implementation</a>. The important snippets below:</p><pre>bit_vector = numpy.zeros(bv_size, dtype=numpy.uint32) for idx in xrange(bv_size): bit_vector[idx] = 0 # reading from file with open(&#39;unsorted_phonebook.txt&#39;,&#39;r&#39;) as ifh: for line in ifh: ph_num = int(line) bit = ph_num % int_size idx = ph_num / int_size comp_int = numpy.uint32(1) comp_int &lt;&lt;= bit bit_vector[idx] |= comp_int with open(&#39;sorted_phonebook_python.txt&#39;,&#39;w&#39;) as ofh: for idx in xrange(bv_size): comp_int = numpy.uint32(1) if bit_vector[idx] &gt; 0: # small optimization for bit in xrange(int_size): if comp_int &amp; bit_vector[idx]: ofh.write(str(idx*32 + bit) + &#39;\n&#39;) comp_int &lt;&lt;= 1</pre><p>The error handling of opening the file is included here showing the nice code density of Python but it’s slow of course (how much slower we’ll see below). Here is a link to the full <a href="https://github.com/rirwin/sandbox/blob/master/scratch/cython-scratch/sort_phonebook_python.pyx">Cython implementation</a>:</p><pre>def sort_phonebook(): DEF bv_size = 321500 # 10M / 32 supports 0 - 9999999 (or ph:999-9999) DEF int_size = 32 cdef int bit cdef int idx cdef int ph_num cdef unsigned int comp_int cdef unsigned int bit_vector_i cdef unsigned int bit_vector[bv_size] for idx in xrange(bv_size): bit_vector[idx] = 0 # reading from file with open(&#39;unsorted_phonebook.txt&#39;,&#39;r&#39;) as ifh: for line in ifh: ph_num = int(line) bit = ph_num % int_size idx = ph_num / int_size comp_int = 1 comp_int &lt;&lt;= bit bit_vector[idx] |= comp_int with open(&#39;sorted_phonebook_cython.txt&#39;,&#39;w&#39;) as ofh: for idx in xrange(bv_size): comp_int = 1 if bit_vector[idx] &gt; 0: # small optimization for bit in xrange(int_size): if comp_int &amp; bit_vector[idx]: ofh.write(str(idx*int_size + bit) + &#39;\n&#39;) comp_int &lt;&lt;= 1</pre><p>Notice how the Cython code is not very different than the Python code! Cython will need to compile this pyx file for Python to call this function. The setup file is here:</p><pre>from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize(&quot;sort_phonebook_cython.pyx&quot;) )</pre><p>And then execute the setup with the following command:</p><p>python setup_cython_phonebook_sort.py build_ext --inplace</p><p>Now we can call this function in another Python program with:</p><pre>import sort_phonebook_cython sort_phonebook_cython.sort_phonebook()</pre><p>For more comprehensive benchmarking, I wrote this algorithm in Java. For brevity, see the java implementation <a href="https://github.com/rirwin/sandbox/blob/master/scratch/cython-scratch/SortPhonebook.java">here </a>.</p><p>On to the performance results. I sorted 6- and 7-digit numbers with these programs.<br> The results for 6-digits:</p><p>$ make<br> python create_phonebook_file.py<br> gcc sort_phonebook.c -o sort_phonebook_in_c<br> javac SortPhonebook.java<br> python setup_cython_phonebook_sort.py build_ext --inplace<br> running build_ext<br> python run_all_tests.py<br> 0.608454942703 seconds to sort in c<br> 1.06622695923 seconds to sort in cython<br> 12.8049960136 seconds to sort in python<br> 1.31410098076 seconds to sort in java<br> diff sorted_phonebook_c.txt sorted_phonebook_cython.txt<br> diff sorted_phonebook_c.txt sorted_phonebook_python.txt<br> diff sorted_phonebook_c.txt sorted_phonebook_java.txt</p><p>The results for 7-digits (I excluded the creation of the file since this is really slow in Python with my current implementation):</p><p>$ make run_tests<br> python run_all_tests.py<br> 4.33113193512 seconds to sort in c<br> 10.2070810795 seconds to sort in cython<br> 130.906479836 seconds to sort in python<br> 10.8574941158 seconds to sort in java<br> diff sorted_phonebook_c.txt sorted_phonebook_cython.txt<br> diff sorted_phonebook_c.txt sorted_phonebook_python.txt<br> diff sorted_phonebook_c.txt sorted_phonebook_java.txt</p><p>A couple of points:</p><p>(1) Confirmed (anecdotally) that the computational complexity growth of these function is mostly linear (10x) going from 6-digit to 7-digit numbers (a 10x growth in number of numbers, 1M to 10M)</p><p>(2) The Python implementation was 20x slower than C for sorting 1M numbers and 30x slower than C for sorting 10M numbers</p><p>(3) Cython edged Java for sorting 1M numbers, but both implementation were 2–2.5x slower than C.</p><p>(4) There are 25 source line of code (SLOC) Python, 35 SLCO for Cython, 51 SLOC Java, 56 SLOC C. There could be argument for performance in terms of this count in terms of developer time.</p><p>There you have it. Try Cython if you have a computationally complex function in Python (or high big-O constants as in this evaluation) that you’d like to avoid re-writing in C or Java. But the ultimate performance king is still C.</p><p><em>Originally published at </em><a href="https://ryaneirwin.com/2014/07/19/cython-performance-case-study/"><em>http://ryaneirwin.com</em></a><em> on July 19, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31838e901251" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Insight Data Engineering Project]]></title>
            <link>https://ryanirwin-2529.medium.com/my-insight-data-engineering-project-2d8542214bff?source=rss-e261d7f133be------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d8542214bff</guid>
            <dc:creator><![CDATA[Ryan Irwin]]></dc:creator>
            <pubDate>Sat, 19 Jul 2014 20:58:37 GMT</pubDate>
            <atom:updated>2020-11-21T04:57:03.960Z</atom:updated>
            <content:encoded><![CDATA[<p>The goal is to analyze historical real-estate listing data using data engineering tools, so I built a tool called Theft Market. I leverage Trulia’s API to gather their historic data. See <a href="http://developer.trulia.com/docs/read/Home">Trulia’s developer page</a> for an overview of their API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*8Lz0MIQeGSjo70az.png" /></figure><p>To bootstrap the data pipeline, Theft Market repeatedly calls Trulia’s API to get the list of states, cities, and zipcodes in the US. It parses the XML responses and puts this information into its Meta Store, a MySQL database. The <a href="https://github.com/rirwin/theft-market/blob/master/trulia-fetcher/TruliaInfoFetcher.py">TruliaInfoFetcher </a>calls getStates, getCitiesInStates, and getZipCodesInState to populate theMeta Store; see <a href="http://developer.trulia.com/docs/read/LocationInfo">information library page</a> for more about these calls.</p><p>With information about different geographic areas, Theft Market repeatedly calls Trulia’s API to get real estate data about each of the areas, which takes approximately 50,000 API calls. The <a href="https://github.com/rirwin/theft-market/blob/master/trulia-fetcher/TruliaDataFetcher.py">TruliaDataFetcher</a> functions used are getStateStats, getCityStats, and getZipCodeStats; see <a href="http://developer.trulia.com/docs/read/TruliaStats">Trulia’s stats library page </a>for more about these calls. The results of these calls are then split in the pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/0*toZscCzP9GJ6byLo.png" /></figure><p>The <a href="https://github.com/rirwin/theft-market/blob/master/trulia-fetcher/TruliaDataFetcher.py">TruliaDataFetcher</a> uses <a href="http://happybase.readthedocs.org/en/latest/">HappyBase </a>to put data directly into HBase (via the Thrift API) when it finishes parsing a stats response. Also, the stats are sent to HDFS using <a href="http://www.fluentd.org/">FluentD </a>to the WebHDFS port on the HDFS NameNode. FluentD appends each record to a file of records in HDFS, and files are partitioned hourly as currently configured. Each line of these record file includes a JSON object for each record allowing flexibility in what was parsed out of the XML.</p><p>Subsequently, these large files in HDFS are processed by Hadoop Streaming with these Python <a href="https://github.com/rirwin/theft-market/tree/master/map-reduce/python">map-reduce jobs</a>. This translates the JSON objects to structured, tab-separated files that are used as Hive external tables. To create the Hive tables, use the create table script; see external table <a href="https://github.com/rirwin/theft-market/blob/master/hive/city/create_ext_table_city.q">creation query</a> for an example to create a city table. One could also write Pig, Cascading, etc. scripts based on the file structure from nice structure of the Hadoop Streaming processing mentioned above. Following that, there are a handful of other ad hoc queries in the <a href="https://github.com/rirwin/theft-market/blob/master/hive/city/">hive directory</a>. This concludes progress on the batch processing, deep-dive analytics layer of Theft Market.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*UVkrohVu3aFI_DDp.png" /></figure><p>The user is exposed to a simple (read-only) REST API for getting statistics about particular geographic areas. The REST call is handed to a combination of Apache (server), WSGI, and Flask. The <a href="https://github.com/rirwin/theft-market/blob/master/server/WebServer.py">Flask </a>has an instance to an object that handles calls to the <a href="https://github.com/rirwin/theft-market/blob/master/common/DatabaseManager.py">MySQL manager</a> and an instance to <a href="https://github.com/rirwin/theft-market/blob/master/common/HBaseManager.py">HBase manager</a>. Apache runs multiple Flask threads, with each thread having its own MySQL and HBase manager. The Flask web server routes calls to functions in the <a href="https://github.com/rirwin/theft-market/blob/master/server/RestCallHandler.py">RestCallHandler </a>. The RestCallHandler coordinates a combination of MySQL and HBase queries to rapidly answer the REST call (see the diagram above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*rkdlnboN3X1ReKYa.png" /></figure><p>The timing of these operations are quite fast. The GPS lat and lon distance query takes about a millisecond, where as the HBase access and the manipulation of a row’s columns takes 100–200 ms depending on how many weeks are in the date range. The columns values are keyed by the date of the week listing (e.g. 2014–06–30) textual json storing the average listing and number of listing that comprise the average (e.g. value=”{‘a’:’1000000′,’n’=’13&#39;}”). The average and number is necessary for recomputing the average over the desired date range.</p><p>The schema could be enhanced to avoid parsing a python dictionary for each key, but this schema leads to acceptable performance with the data I have; I noticed that Trulia’s historical data goes back to at most 2008 (so that is 52 days/year * 6 years = 312 maximum columns per row). I also don’t take advantage of using different column families for other attributes I would not often access with listing averages.</p><p>The API format is straighforward, the caller passes a dictionary (described below) to a base url corresponding to the query interest; here are the following urls supported:</p><p>- <em>ipaddress</em>/data/city/volume<br> — <em>ipaddress</em>/data/city/average<br> — <em>ipaddress</em>/data/zipcode/volume<br> — <em>ipaddress</em>/data/zipcode/average</p><p>where volume is the aggregation of listings over the time period and average is the average listing price over the time period. The dictionary passes the remainder of the search parameters. All dictionaries contains the following key-value pairs:</p><p>- start_date (YYYY-MM-DD)<br> — end_date (YYYY-MM-DD)<br> — num_bedrooms (positive integer)</p><p>For city queries provide:</p><p>- state_code (XX)<br> — city ( <em>city name</em>) (some browsers may need a ‘%20’ inserted for spaces in the city name)</p><p>For zipcode queries provide:</p><p>- zipcode (XXXXX)</p><p>A full example of a city average listings call:</p><p><em>ipaddress</em>/data/city/average?q={&quot;state_code&quot;:&quot;MA&quot;,&quot;city&quot;:&quot;Boston&quot;,&quot;num_bedrooms&quot;:3,&quot;start_date&quot;:&quot;2012-01-01&quot;,&quot;end_date&quot;:&quot;2014-01-01&quot;}</p><p>A full example of a zipcode volume listings call:</p><p><em>ipaddress</em>/data/zipcode/volume?q={&quot;zipcode&quot;:&quot;02458&quot;,&quot;num_bedrooms&quot;:3,&quot;start_date&quot;:&quot;2012-01-01&quot;,&quot;end_date&quot;:&quot;2014-01-01&quot;}</p><p>Overall, this was a really fun project with a functioning prototype with 2–3 weeks of work. Some issues I had was using the Thrift API to put data into HBase. I would have used the Java API if I had known how flaky it is. Also, having port 80 open on Amazon Web Services machines is asking for trouble. I saw dozens of different types of access from the Apache server access log from researcher’s web crawlers to a commonly known w00tw00t attack. I’d need learn how to configure Apache to not crash on seemingly simple gets (here I thought Apache was a more hardened server platform than Flask).</p><p>Right now the project is off-line because AWS costs money. The 4-node (1 x1large, 3 x1mediums) were paid for by Insight. I’d like to see if I could get the Rest API portion of this project on a single node with decent performance soon. Without a doubt I will be distracted by working hard getting started at my next job (to be determined).</p><p><em>Originally published at </em><a href="https://ryaneirwin.com/2014/07/19/my-insight-data-engineering-project/"><em>http://ryaneirwin.com</em></a><em> on July 19, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d8542214bff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>