<?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 Edison Wang on Medium]]></title>
        <description><![CDATA[Stories by Edison Wang on Medium]]></description>
        <link>https://medium.com/@edison-wang?source=rss-3683b7ef50a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*MpSn5BTWA61hv7YUuClo3A.jpeg</url>
            <title>Stories by Edison Wang on Medium</title>
            <link>https://medium.com/@edison-wang?source=rss-3683b7ef50a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:09:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@edison-wang/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[Sending data between applications]]></title>
            <link>https://medium.com/codex/sending-data-between-applications-e08fb0028a71?source=rss-3683b7ef50a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e08fb0028a71</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[application-development]]></category>
            <dc:creator><![CDATA[Edison Wang]]></dc:creator>
            <pubDate>Thu, 25 Mar 2021 06:44:15 GMT</pubDate>
            <atom:updated>2021-03-26T02:12:01.129Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://medium.com/codex">CODEX</a></h4><h3>5 Ways To Share Data Between Applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*igwM3QDjAxivM45b" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>It’s a common scenario to transfer data between 2 applications on a regular basis, e.g sending Purchase Order data from a web application to another. This article introduces a few common ways of data transfer between 2 web applications.</p><h4>API Payload</h4><p>If the data is small and immediate response is required, the easiest way is using a API.</p><p>For example, sending a purchase order data from the web application to an accounting application. The accounting application exposes a REST API to accept purchase order. The purchase order data can be base64 encoded(safe inclusion in payload) and added to the POST payload with other information and then posted to that REST API. The REST API will respond with a 200 status code indicating it has accepted the purchase order data.</p><p>This is a popular and simple approach. Application can control full flow of data transfer: sending, receiving, error handling, retrying etc.</p><p>However, there is a size limit with REST API payload, that is 128MB(in reality, you will never want to post anything close to that size anyway). The posting process will have to wait for the response of this API call and it might affect the user experience/performance of web app. This approach is not a good choice for sending large data or burst of data.</p><h4>Message Queue</h4><p>Using a message queue service such as Rabbit MQ can be an elegant way of sending data asynchronously.</p><p>See my other article if you want to implement MQ with Python in <a href="https://python.plainenglish.io/celery-task-queue-with-aws-sqs-dd51f350ae50">here</a>.</p><p>The size limit is quite large (a few GB in theory, but in reality, smaller data is preferred in MQ). The sender doesn’t have to wait for the response(asynchronous), it just registers message in the queue. The receiver picks up message from the queue when it’s free.</p><p>This is suitable for handling burst of data or when the receiver takes a bit time to handle messages.</p><p>For example, if your website receives a high volume of purchase orders in short period of time and it needs some extra processing like receipt PDF generation, you might consider using a MQ to offload those orders data to another application for PDF processing. User doesn’t have to wait for the whole process to finish while he places the order.</p><p>But keep in mind that, MQ doesn’t provide a response for task processing. Either forget about getting the response, or you will have to poll the response/status in your application. You will also need to be careful of a blocking task in the queue, because that will block the entire queue.</p><h4>Message Streams</h4><p>Similar to MQ, but in order to handle even larger number of data transfer(higher traffic) and process them in bulk(instead of 1 message per event), a message stream service such as AWS Kinesis, Apache Kafka might be more appropriate.</p><p>They are often used in real time data analysis and machine learning applications, when real time data feed such as Twitter tweets, user comments etc, to be quickly transferred to application in batches for analysis.</p><h4><strong>S3 Bucket (cloud storage)</strong></h4><p>Data in large size is best to be stored in files (and if it is generated as a file, it’s best to stay as a file).</p><p>For example, if your web application generates a PDF and needs to send it over to another application for processing. In this case, the web app can upload it to AWS S3 bucket and store it there. The other application could pull the file from S3 bucket and process it.</p><p>However S3 bucket alone doesn’t provide an arrival notification system, neither it provides a way of managing files as a queue. Your application is responsible for managing the files there, such as finding out files to process, move it to processed folder when it’s done etc.</p><p>With AWS, you can setup Kinesis stream with S3 bucket to serve as file events system. When a new file is uploaded there, it would trigger an event in the stream, and fire up a AWS Lambda function, so the function could process the uploaded file.</p><h4>Shared database</h4><p>Aka. dirty and quick way. Sharing data between a web application and a Lambda function could be as simple as just making them sharing the same Database and reading from the same data table.</p><p>But be careful of implications here, especially both of them are writing to the same database. It could cause confusions and problems when developer working on one application not being aware of writes from another application.</p><p>It also means that it’s difficult for application code to handle/hook to the message receiving process.</p><h4>Summary</h4><p>This article introduced a few common way of sharing data in web applications. There are a couple of less common ways I wouldn’t cover here, such as RPC, RSS feed etc.</p><p>Fewer moving parts, the less likely things would break. Use the strategy suits your need. Let me know if you have any question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e08fb0028a71" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/sending-data-between-applications-e08fb0028a71">Sending data between applications</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celery Task Queue with AWS SQS]]></title>
            <link>https://python.plainenglish.io/celery-task-queue-with-aws-sqs-dd51f350ae50?source=rss-3683b7ef50a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd51f350ae50</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Edison Wang]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 05:33:38 GMT</pubDate>
            <atom:updated>2021-03-14T08:12:11.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YnUsyt3zYALFD9fe" /><figcaption>Photo by <a href="https://unsplash.com/@dosejuice?utm_source=medium&amp;utm_medium=referral">Dose Juice</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Celery is a great and simple Task Queueing system for Python. It allows you to offload heavy tasks to another server and run it asynchronously. It can also run periodic tasks too. It’s also surprisingly easy to setup with AWS Simple Queue Service(if your app is hosted with AWS).</p><h4>Why would you need a queueing system?</h4><p>I have been looking for a task queueing system for primarily 2 scenarios</p><ol><li>Upload files to AWS S3 in the background, without affecting frontend user experience. The upload task could take seconds, and there could be high demand in frontend. This should be offloaded to a dedicated server and executed asynchronously without holding on user to wait.</li><li>Periodic side tasks such as sending a report email every night. Ideally this should be offloaded without affecting main application server.</li></ol><h4>What use AWS SQS?</h4><p>Celery requires a message broker to transmit tasks. Initial, I setup Celery with RabbitMQ because of its reputation. But then I realised there is a much simpler solution. If you host your app with AWS already, it’s almost 0 effort to setup AWS SQS as the message broker. It doesn’t require a dedicated deployment for the message broker at all, it’s an always-on service!</p><p>With RabbitMQ, it usually requires a dedicated hosting server, which is a pain to setup.</p><h4>Get started</h4><p>We will need a dedicated Celery deployment to pick up and execute tasks. Below is the partial docker file to spin off this Celery deployment. Note that I defined queue name as scheduled_jobs_queue and enabled celerybeat for periodic scheduling. The tasks are defined in file celery_scheduled_job.tasks.</p><p>The last CMD runs the celery daemon/executor that listen for the incoming tasks and then execute it.</p><pre>... setup your deployment as usual then ...<br>RUN mkdir -p /var/run/celery /var/log/celery</pre><pre>RUN groupadd -r celery &amp;&amp; useradd --no-log-init -r -g celery celery</pre><pre>RUN chown -R celery:celery /var/run/celery /var/log/celery</pre><pre>RUN chown -R celery:celery /root</pre><pre>RUN chmod 755 -R *</pre><pre>CMD /venv/bin/celery -Q scheduled_jobs_queue -A celery_scheduled_job.tasks worker -B -n scheduled@%%h --uid=celery --gid=celery --statedb=/var/run/celery/worker@%h.state -s /var/run/celery/celerybeat-schedule</pre><h4>Define Celery tasks</h4><p>This file(celery_scheduled_job.tasks) must exist in both the Celery deployment and your application deployment(caller deployment).</p><pre>app = Celery(&#39;scheduled_jobs&#39;, broker=&#39;sqs://</pre><pre>&#39;, include=[&#39;celery_scheduled_job.tasks&#39;])<br></pre><pre>app.conf.broker_transport_options = {&quot;queue_name_prefix&quot;: f&quot;{env_name}-&quot;}</pre><pre>&quot;&quot;&quot;Set up periodic tasks&quot;&quot;&quot;</pre><pre>@app.on_after_configure.connect</pre><pre>def setup_periodic_tasks(sender, **kwargs):</pre><pre>  sender.add_periodic_task(</pre><pre>  # 6pm Sydney time send a new orders report.</pre><pre>  crontab(hour=8, minute=00,    day_of_week=&#39;mon,tue,wed,thu,fri,sat,sun&#39;),</pre><pre>  new_order_report.s(),</pre><pre>)</pre><pre>&quot;&quot;&quot;Define asynchronous tasks here&quot;&quot;&quot;</pre><pre>@app.task(</pre><pre>queue=&#39;scheduled_jobs_queue&#39;,</pre><pre>bind=True,</pre><pre>soft_time_limit=120,</pre><pre>max_retries=5</pre><pre>)</pre><pre>def upload_file_to_s3(self, filename=None, data=None):</pre><pre>  try:</pre><pre>    upload_file(filename=filename, data=data)</pre><pre>  except Exception as exc:</pre><pre>    logger.error(f&quot;Error when sending file to S3: {exc}&quot;)</pre><pre>  raise self.retry(exc=exc)</pre><p>Note that, the <strong>broker URL </strong>is simply defined with an URL <em>sqs://.</em> Celery would automatically connect to AWS SQS service given AWS service keys are available in the environment variables.</p><p>The <strong>queue_name_prefix</strong> would allow you to create/use separate queues for different environments, e.g prod-{queue_name}, dev-{queue_name}</p><p>The queue in SQS will be automatically created by Celery, there is no initiation process required!</p><p>The periodic task is defined and scheduled with crontab. The asynchronous upload task is defined in upload_file_to_s3().</p><p>Notice that, both of them have a config of queue=’scheduled_jobs_queue’. So both of the them share the same queue(Since I only setup 1 Celery deployment. AFAIK, it can only listen to 1 queue)</p><p>The config of <strong>soft_time_limit, max_retries</strong> etc are there to make sure it tries a couple of times to upload file before timeout exception, and continue with other tasks in queue instead of blocking the queue on failure.</p><h4>The caller code</h4><p>In your web application code, invoke the asynchronous task like below.</p><pre>upload_file_to_s3.delay(filename, data)</pre><p>The delay() schedules this function run with Celery asynchronously. Without delay(), you are invoking the function directly!</p><p>The periodic task doesn’t need a caller(obviously), as it’s scheduled already on the Celery deployment.</p><h4>The gotcha</h4><p>When you invoke a Celery task with .delay(), the parameters would be base64 encoded by Celery into the queue message. This means, it can accept basic data type, such as string, array. But if you pass a function object into parameter, like a callback function, it wouldn’t work.</p><h4>Final words</h4><p>I have been running this architecture for a couple of months so far. I ran across a couple of issues, hence those config params adjustment. But after that, it perfectly catches and executes every task even in higher-than-usual traffic time when hundreds of tasks were queued up in SQS, it would handle it with grace.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd51f350ae50" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/celery-task-queue-with-aws-sqs-dd51f350ae50">Celery Task Queue with AWS SQS</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Moving to Python From PHP]]></title>
            <link>https://medium.com/swlh/moving-to-python-from-php-eb9dfa798e8f?source=rss-3683b7ef50a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb9dfa798e8f</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[job-market]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Edison Wang]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 01:57:32 GMT</pubDate>
            <atom:updated>2020-09-29T05:36:59.270Z</atom:updated>
            <content:encoded><![CDATA[<p>I have been a PHP developer(and fan) for a decade. It formed my perspective on what a programming language should be. Now I’m joining the Python camp and here are my reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q-LikG1uxPkgj_14" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=medium&amp;utm_medium=referral">Hitesh Choudhary</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Neat Code</strong></h3><p>How many times do you have to rub your eyes and look closer to match the ending brackets of statements?</p><p>I did it everyday when coding with PHP. Before a proper IDE came into play, I literally placed a ruler on monitor screen to vertically line up brackets!</p><p>Here is an example of statements in PHP</p><pre>function hello($arg)   {<br> if ($arg) {<br>   if ($arg === &#39;hello&#39;)  {<br>        print(&#39;world&#39;)<br>    } else {<br>        print(&#39;!&#39;)<br>    }<br>   }<br> }</pre><p>Here is the same code in Python</p><pre>def hello(arg):<br>    if arg:<br>        if arg == &#39;hello&#39;:<br>            print(&#39;world&#39;)<br>        else:<br>            print(&#39;!&#39;)</pre><p>That’s right, Python uses indentation to group statements. Correct indentation is enforced throughout code. It might not be a big deal for a code snippet. But with larger code base, you will appreciate the neatness and readability this brings in.</p><p>Imagine you are reviewing Pull Request from your co-worker, the code is filled with brackets with inconsistent format, indentation and spaces before/after brackets, you will have a hard time lining up brackets and reading the code.</p><p>You would wish all developers are forced to use a lint tool with same coding standard, but this is not the case in reality.</p><p>Neat code will help us focus on code logic rather than formatting and brackets.</p><h3><strong>Easy List Manipulation</strong></h3><p>In Python world, processing data structure(such as list and dictionary etc) is made so simple. Processing data structure is such a daily routine for every developer, it would save us lots of time if it can be done easier.</p><p>Below code snippet finds even numbers in a list.</p><p>In Python</p><pre>def find_even (numbers):<br>    return [num for num in numbers if (num % 2) == 0]</pre><p>In PHP</p><pre>function find_even ($numbers) {    <br>    $results = [];<br>    foreach ($numbers as $num) {<br>        if (($num % 2) === 0) {<br>            $results[] = $num;<br>        }<br>    }<br>    return $results<br>}</pre><p>Basic arrays manipulations in Python</p><pre>a = [1, 2, 3]<br>b = [4, 5, 6]</pre><pre># Merge 2 arrays.<br>c = a + b</pre><pre># New array sliced from 3rd and 4th elements.<br>d = c[2:4]</pre><pre># Reverse whole array. [start:stop:step]<br>e = d[::-1]</pre><p>Same code in PHP</p><pre>$a = [1, 2, 3];<br>$b = [4, 5, 6];</pre><pre># Merge 2 arrays.<br>$c = array_merge($a, $b)</pre><pre># New array sliced from 3rd and 4th elements.<br>$d = array_slice($c, 2, 2);</pre><pre># Reverse array.<br>$e = array_reverse($d);</pre><p>The syntax in Python is so neat and powerful(without need of external functions). It might look a little confusing in the beginning (as it did for me), but soon you will find writing this kind of syntax is easy and time-saving for little tasks like this.</p><p>What’s making Python data processing more powerful are packages, such as Numpy.</p><pre>import numpy as np</pre><pre># Make up an array with evenly spaced values stop to 6.<br>a = np.arange(6)<br>print(a)</pre><pre># Output<br>[0,1,2,3,4,5]</pre><pre>b = a.reshape(3, 2)<br>print(b)</pre><pre># Output<br>[[0,1],[2,3],[4,5]]</pre><pre># repeat number 1 5 times<br>np.repeat(1,5)</pre><pre># Output<br>[1, 1, 1, 1, 1]</pre><h3><strong>Data Science</strong></h3><p>Python is the most popular programming language in the data science world thanks to the tools it offers, the community it is based on and also the ease of use and simple syntax which makes it easy to adapt for people who do not have an engineering background.</p><p>When I was learning data science online, I have been exposed to Python tools/packages such as Jupyter Notebook, Scikit-learn, Pandas, Numpy and Spark. The course is designed around Python. As a result, I have to learn a great deal of Python. The communities like Kraggle and medium helped me a lot on data science learning.</p><p>There is simply no such thing in PHP world.</p><p>While PHP is great for web dev, if you are going towards data analysis/science, you will have to learn another language.</p><h3>Great for Micro-service</h3><p>While PHP and a heavyweight MVC framework such as Laravel are perfect partners for building a traditional website.</p><p>The software architecture today is shifting to an agile, micro-service pattern. You are required to code light-weight micro-service, quick PoC, a MVP service, a quick Lambda function etc, deployed on cloud, exposed as API.</p><p>If you are going with PHP, you have to stick with a EC2 or similarly hosted full-on service, with Docker images and framework built in, which is too heavy.</p><p>On the other hand, Python or JS that is natively supported by AWS Lambda and great for small tasks. You would prefer all of your code written in same language, so Python/JS becomes an agile all-rounder in the cloud.</p><p>All of these reasons make Python and lightweight framework standing out as a good choice for micro-service.</p><h3>Performance</h3><p>Latest version PHP is slightly faster than Python in terms of execution speed(marginally), given they are both interpreted programming languages .</p><p>I used to be thrilled by the performance gains of PHP over last couple of years, especially from PHP 5 to PHP 7 (lab figure about 30% faster). But in today’s cloud computing world, it is becoming less of a concern.</p><p>The biggest performance bottleneck of your application could be coming from your app architecture, cloud infrastructure, network, lack of cache or maybe even a block of your code.</p><p>I hardly hear anyone complaining about a programming language’s execution speed these days. It’s more likely other factors would cause a performance problem rather than the language itself.</p><p>Is a web app faster when built in Java vs PHP or Python? I don’t think it would be a fair comparison given there are way more important factors there and they are different in many ways.</p><p>My understanding is Python is fast enough and optimised for today’s web application.</p><h3>Job Market</h3><p>The mindset in job market right now is that PHP is for building traditional website and it is a little out-dated. Therefore the pay range is usually lower than trending language such as Python.</p><p>It is true that a good developer can master any language However it is undeniable that Python is a sought-after language in today’s market because it is a key skill to have for booming areas such as cloud, AI, data science, cryptocurrencies and more.</p><p>And you want to future-proof your career. So you might want to consider starting to learn Python.</p><h3>Easy to Learn</h3><p>With years of experience coding with PHP and JS, it doesn’t take long for me to confidently write Python code and try to do it in Pythonic style.</p><p>Tricky concept like decorator is similar to that of functional composition of JS. You can always find similarities with your existing skillset. Although it might take some time to learn framework, libraries and tools in Python, the language itself is quite sweet to pick up.</p><h3>Summary</h3><p>There are plenty of articles out there comparing PHP with Python in terms of feature and tech characteristics, and one with another. Most of them are tech focused. I offered my opinions from a software developer’s perspective as I switched from PHP to Python for my career.</p><p>I was really impressed by the neatness and agileness of Python and excited by its possibilities with AI and data science. It is also trending in job market and turns out easy to learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb9dfa798e8f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/moving-to-python-from-php-eb9dfa798e8f">Moving to Python From PHP</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres Recursive Query(CTE) or Recursive Function?]]></title>
            <link>https://medium.com/swlh/postgres-recursive-query-cte-or-recursive-function-3ea1ea22c57c?source=rss-3683b7ef50a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea1ea22c57c</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[trees]]></category>
            <category><![CDATA[cte]]></category>
            <dc:creator><![CDATA[Edison Wang]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 11:57:29 GMT</pubDate>
            <atom:updated>2020-04-25T10:38:15.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*TbCym-tk2apXVr2S8BgcnQ.png" /></figure><p>If you ever googled how to recursively find records with Postgres SQL, for example, traversing a tree stored in a table, you will find ALL suggestions point you to Postgres Recursive Query with Common Table Expressions (CTE).</p><p>The mentality around this, as a Stack Overflow thread suggests, is “You don’t need a function at all, this can be done with a single SQL statement”. It is true in most cases, but is Recursive Function so bad? This article compares both approaches in terms of performance, complexity, limitation etc. In one use case, Recursive Function actually performs much better than CTE. So read on.</p><h3>What is Recursive CTE and Recursive Function?</h3><p>I highly recommend reading the <a href="https://www.postgresql.org/docs/current/queries-with.html">Postgres docs </a>before trying to write your first recursive query. A few years ago when I first stumbled on a complex recursive query, I was puzzled how this recursive mechanism would ever work because it doesn’t look like a traditional recursion function where a function calls itself and the deepest level gets executed first. But this query I saw is everything but working in a recursive way.</p><p><strong><em>Postgres Recursive CTE is a iteration not recursion</em></strong></p><p>It turns out it’s actually a iteration process. Postgres would just repeatedly execute the recursive part of this query until there is no more result returned.</p><p>Below is an example of a Recursive CTE showing 0–500 integers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ij9ooXJmebJExrZjWQzpkQ.png" /><figcaption>select 0–500 integers with recursive CTE</figcaption></figure><p>The static part is SELECT 0 which is executed once. The recursive part after the UNION is repeatedly executed and merged to results.</p><p>On the other hand, a recursive function is basically just a normal Postgres function executed recursively(invoking itself). Below example shows the recursive function achieving the same result as above recursive CTE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpGGD2Fiv73HRKgCF5iAcA.png" /><figcaption>select 0–500 with recursive function</figcaption></figure><h3>A simple use case</h3><p>The above examples can be observed as a simple use case. It does not involve large tables, neither complex operations nor table joining.</p><p>The performance difference is trivial. Recursive CTE takes 18.46 ms and recursive function takes 42.54 ms. However the recursive CTE is still a bit faster, neater and convenient as it’s just a SQL.</p><p>In this case, the Winner is <strong>Recursive CTE.</strong></p><h3>Traversing a tree</h3><p>Let’s look at a more complex scenario. I have created a simple tree table storing tree nodes with only 2 columns (id and child id). There are 500 tree nodes (rows) in it. Each node is uniquely linked to another node in the table.</p><p>The goal is to find all children nodes given a node id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPB5z-EC6CkX75K8tV_9CQ.png" /><figcaption>Tree table</figcaption></figure><h4>Implementation with recursive CTE</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R08Vz_ARys5f7sHVxOLqyw.png" /><figcaption>Recursive CTE implementation</figcaption></figure><pre>QUERY PERFORMANCE ANALYSIS<br>--------------------------</pre><pre>CTE Scan on recursive_query  (cost=113.31..115.33 rows=101 width=8) (actual time=0.686..1257.405 rows=500 loops=1)<br>   CTE recursive_query<br>     -&gt;  Recursive Union  (cost=0.27..113.31 rows=101 width=8) (actual time=0.680..1254.706 rows=500 loops=1)<br>           -&gt;  Index Scan using idx on my_tree  (cost=0.27..8.29 rows=1 width=8) (actual time=0.664..0.670 rows=1 loops=1)<br>                 Index Cond: (id = 0)<br>           -&gt;  Hash Join  (cost=0.33..10.30 rows=10 width=8) (actual time=1.301..2.487 rows=1 loops=500)<br>                 Hash Cond: (t.id = recursive_query_1.child_id)<br>                 -&gt;  Seq Scan on my_tree t  (cost=0.00..8.00 rows=500 width=8) (actual time=0.009..1.225 rows=500 loops=500)<br>                 -&gt;  Hash  (cost=0.20..0.20 rows=10 width=4) (actual time=0.013..0.013 rows=1 loops=500)<br>                       Buckets: 1024  Batches: 1  Memory Usage: 9kB<br>                       -&gt;  WorkTable Scan on recursive_query recursive_query_1  (cost=0.00..0.20 rows=10 width=4) (actual time=0.003..0.005 rows=1 loops=500)<br> Planning time: 0.688 ms<br> Execution time: 1259.438 ms</pre><p>The query looks neat. However, the performance isn’t as great as I expected. It took whole <strong>1259.438 ms </strong>(almost 1.3 second!). A closer look shows that the slow parts are</p><ul><li>500 recursions. Each recursion invokes tree table sequence scan to find children. Seq Scan on my_tree t (cost=0.00..8.00 rows=500 width=8) (actual time=0.009..1.225 rows=500 loops=500)</li><li>500 unions for merging new results with existing results</li></ul><p>Let me explain it better. The query would repeat the recursive part to find a node’s children until there is no more children returned. In this case it’s repeated 500 times because there are 500 nodes in the tree table and each one is uniquely linked to another, so it has to iterate 500 levels to find the last child.</p><p>Postgres decides to use a Sequence Scan(scans every entry of table) on the tree table instead of using optimized Index Scan (Index can be seen as a way of caching results to speed up bulk reads). So scanning table 500 times on a 500 rows table caused a big performance hit.</p><p>The union of merging recursion results with existing rows also adds more performance hits. The overall performance is actually quite poor considering it isn’t even a massive table. When the table gets larger, the performance could be even worse.</p><p>It’s <strong>so slow</strong>. In reality, if your application is trying to frequently and recursively find children nodes in this way, you should re-consider your strategy! You can probably completely avoid recursive stuff if parent/child relation can be stored in a string structure. I won’t cover details in this article.</p><h4>Implementation with recursive function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIZbpLlJxyUWK_o4pc0Lgg.png" /><figcaption>Implementation with Recursive Function</figcaption></figure><pre>QUERY PERFORMANCE ANALYSIS<br>--------------------------<br> Function Scan on recursive_function  (cost=0.25..10.25 rows=1000 width=8) (actual time=132.234..133.347 rows=500 loops=1)<br> Planning time: 0.062 ms<br> Execution time: 134.489 ms</pre><p>It’s a black box as I used EXPLAIN ANALYSE to inspect the query performance. There is no easy way to inspect what’s going on in the function. But the fact is, it’s a much faster process than recursive CTE.</p><p>My guess is that, all queries used in this function use conditions like WHERE A.id = my_id which allows Postgres to use table Index instead of having to scan whole table. This significantly speeds up the process of finding children.</p><p>In this specific case, <strong>Recursive Function</strong> is the winner.</p><h3>Traversing a larger tree</h3><p>I increased the tree table to 1000 rows. This means recursion has to happen 1000 times to reach the last child.</p><p>The recursive CTE returns under 5.4 Seconds. (It’s a local DB hosted on my slow computer after all)</p><p>But the recursive function gives me ERROR: stack depth limit exceeded. HINT: Increase the configuration parameter “max_stack_depth” (currently 2048kB), after ensuring the platform’s stack depth limit is adequate.</p><p>If you don’t know how many levels it can go and potentially it can invoke a large number of recursions, don’t use Recursive Function. You wouldn’t like it when this error happens on production.</p><p><strong><em>Recursive function has a max depth limit</em></strong></p><p>This error also indicates that a recursive function MIGHT use a lot of memory as it creates a new function context when it goes deeper. A recursive CTE uses iterations, so all work is done in the same context. It might use less memory.</p><p>Recursive CTE a winner in this case.</p><h4>Conclusion</h4><p>In this article I have studied a few scenarios where both Recursive CTE and Recursive Function can be applied.</p><p>Recursive CTE is simpler to write but performance isn’t great due to failing to use Index. Recursive Function is faster but limited by recursion depth as it might use more memory.</p><p>In reality, you should consider both approaches and focus on performance outcome. Optimize your query to use table Index if possible. If you could, avoid using recursive stuff at all to minimize performance implication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea1ea22c57c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/postgres-recursive-query-cte-or-recursive-function-3ea1ea22c57c">Postgres Recursive Query(CTE) or Recursive Function?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving a Mix of Public and Private S3 Content Through AWS CloudFront]]></title>
            <link>https://medium.com/geekculture/serving-a-mix-of-public-and-private-content-of-s3-through-aws-cloudfront-e158684f828a?source=rss-3683b7ef50a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e158684f828a</guid>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[private-content]]></category>
            <category><![CDATA[signing-url]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[aws-cloudfront]]></category>
            <dc:creator><![CDATA[Edison Wang]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 12:12:44 GMT</pubDate>
            <atom:updated>2021-03-23T22:13:19.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="AWS CloudFront is a CDN" src="https://cdn-images-1.medium.com/max/681/1*r6oWjjc5kS2PS7KswVvVsw.jpeg" /></figure><p>AWS CloudFront is a CDN web service to distribute your static content via its edge locations to speed up the content delivery. Many companies have a requirement to deliver a mix of<strong> private and public</strong> content from their S3 bucket, however I find AWS guide isn’t very clear on that. I’m writing this article to share a few tips I&#39;ve learned.</p><p>AWS secures private content by either Signed URL or Signed Cookie. This article will focus on the Signed URL as it’s more versatile. Signed Cookie is very similar to Signed URL anyway.</p><p>Before diving into technical details, let’s be clear on URL signing. CloudFront supports a way of granting temporary access of private content to end-user by signing a content URL with a condition, normally it is an expiry timestamp. Thus an end-user can access the signed content URL within a limited time period.</p><p>To sign a file URL, you will need a pair signing keys: A private key for your application to sign a file URL and A public key for CloudFront to verify the signed URL.</p><ul><li><strong><em>Only AWS Root User can generate a pair of CloudFront Signing Keys</em></strong></li></ul><p>If you are not a Root user (most company don’t give developers root credentials), you should ask about it before starting this. It might be a tall ask, but CloudFront is a special AWS service across all regions, there might be security reasons for this.</p><p>The key pair can be generated and downloaded in root user account security credentials page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*a79IDwHEJy2hqVl3pQN6Vg.jpeg" /></figure><h4>Create a S3 bucket</h4><p>Assuming your private and public content both exists in an S3 bucket, your will need to separate those content to different locations. If public and private content are already in different buckets, that’s fine too, read on. If there is no way to separate public and private files in S3 bucket, there might not be a way for CloudFront to tell which files are public or private.</p><ul><li><strong><em>Public and private files should be in separated S3 locations</em></strong></li></ul><p>But why? CloudFront uses the S3 location path as part of the CDN URL. When CloudFront receives a user request, it has no knowledge of your application-level permissions of the requested file. Putting public files in a public folder, allows CloudFront to easily identify it’s a public file based on URL path, so it can lift Signed URL policy on that folder only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*LTVz3_Z4kO-midFN1Q3hMw.jpeg" /></figure><p>In my example above, public files exist in a public folder, everything else are private files. You can use other ways of organizing public/private files in your S3 bucket, but the principle is that it should allow CloudFront to identify public/private path easily.</p><ul><li><strong><em>Block public access to your entire S3 bucket</em></strong></li></ul><p>We need to make sure CloudFront can READ from this S3 bucket but there should be absolutely NO public access to this bucket. This is important because a public accessible S3 bucket allows end user to bypass CloudFront to access restricted file directly.</p><p>Go to permission tab of your S3 bucket and block all public access. (You might need to allow your application to write to this bucket though)</p><p>CloudFront would use a special feature, <strong>Origin Access Identity</strong>, to gain access of the S3 bucket.</p><p>Below diagram illustrates what we are trying to achieve</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*vxE-NmB3M5kbwdB2.png" /></figure><ol><li>Signed URL to restrict access to file caches</li><li>Restricted access to objects in your S3 bucket to CloudFront only</li></ol><h4>Create CloudFront Distribution</h4><p>Go to AWS CloudFront page, click Create New Distribution . Select your S3 bucket URL as the Origin Domain Name. Make sure you enabled Restrict Bucket Access and a new Origin Access Identity is added to Bucket Policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*5-aUDJQkTgKulf8NvswQLw.jpeg" /></figure><p>Restrict Viewer Access must be enabled. If you are the Root user, the Trusted Signer would be self.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*65yFEqlc4xqy1EqhWfqj7w.jpeg" /></figure><p>You can leave all rest options as default. After a distribution is created, wait for the Status of the distribution to be ready if you want to test it. It might take minutes to half an hour, depending on deployed locations.🙄</p><h4>New Cache Behavior to allow public access</h4><p>Now we have all files restricted for URL signing. How about our public files?</p><p>Click Behavior, Create a new Behavior. Make sure it has below configurations.</p><p><strong>Path Pattern: </strong>public/*<br><strong>Restrict Viewer Access: </strong>No</p><p>This allows files matching pattern&lt;your CloudFront URL&gt;/public/* to be public accessible through this CloudFront distribution.</p><p>If you use another S3 bucket for public files instead of a folder under same bucket, you need to create another Origin for that public bucket and create a cache Behavior for that Origin only to disable Viewer Access.</p><h4>Signing file URL</h4><p>The signing algorithm is just standard RSA SHA-1 algorithm. Your application can sign it without having to require AWS tools.</p><p>There is 2 ways of signing, canned policy or custom policy. If all you need to do is signing an individual file one at a time. Just use canned policy. Custom policy is useful for signing multiple files in one go.</p><p>There is Code Example on <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateCFSignatureCodeAndExamples.html">AWS guide</a> to demonstrate signing process.</p><h4>Re-use signature for multiple files</h4><p>When it comes to signing a bunch of files, for example, a collection of files under a folder. It puzzles me a lot how to do it efficiently and correctly. AWS guide is not very clear when it mentions “You can reuse the policy statement for multiple files”.</p><ul><li><strong><em>You can re-use the signature for all allowed files with custom policy</em></strong></li></ul><p>If you have many private files in a folder and you need to serve all that to user, you should use custom policy granting access to the whole folder, and re-use the generated signature for all granted files. The signing process only signs the custom policy itself, so the result signature is just identical to all files.</p><p>The custom policy should be like</p><pre>{<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Resource&quot;:&quot;http://d111111abcdef8.cloudfront.net/training/*&quot;,<br>      &quot;Condition&quot;:{&quot;DateLessThan&quot;:{&quot;AWS:EpochTime&quot;:1357034400}}<br>    }<br>  ]<br>}</pre><p>Above policy would generate a signature that can be appended to all file URLs in the training folder.</p><h4>Serving file to end user</h4><p>Now you are almost done. The signature should be appended to the CloudFront CDN URL, and provided to user. The full signed URL looks like below.</p><pre>http://d111111abcdef8.cloudfront.net/training/image.jpg?Policy=&lt;base64 policy&gt;&amp;Signature=&lt;base64 policy&gt;&amp;Key-Pair-Id=&lt;key id&gt;</pre><p>And finally, you might want to set your application domain to replace the default random CloudFront CDN URL, as it doesn’t look very nice.</p><p>Good luck and may the git push --force be with you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e158684f828a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/serving-a-mix-of-public-and-private-content-of-s3-through-aws-cloudfront-e158684f828a">Serving a Mix of Public and Private S3 Content Through AWS CloudFront</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>