<?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 Xuan on Medium]]></title>
        <description><![CDATA[Stories by Xuan on Medium]]></description>
        <link>https://medium.com/@xuan11290?source=rss-4898d0bb4f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7dJxkC_DJoTscl8L</url>
            <title>Stories by Xuan on Medium</title>
            <link>https://medium.com/@xuan11290?source=rss-4898d0bb4f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:53:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xuan11290/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[Making candies algorithm and math proof]]></title>
            <link>https://medium.com/@xuan11290/making-candies-algorithm-and-math-proof-eaa03941696d?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaa03941696d</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 14:16:10 GMT</pubDate>
            <atom:updated>2023-12-21T14:16:10.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ALNutw2g5JyRmHultXNxtA.png" /></figure><p><strong>We have W workers, and each worker can produce 1 candy per day. It costs P candies to hire 1 additional worker.</strong></p><p><strong>Determine the minimum number of days required to produce N candies.</strong></p><p>The main point of this problem is that you need to determine the most efficient way to allocate candies to purchase additional workers versus retaining them to meet the production goal.</p><p>Suppose that we have the best solution to have <strong><em>N</em></strong> candies after <strong><em>r</em></strong> steps (<strong><em>r</em></strong> is the minimum days to have <strong><em>N</em></strong> candies).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KwVw3djuLlVCzxC6BuO2wQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIfEF-nR9Bd9uaTvyqQ1aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMDvE5DjnfUYu51lySqasQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2nWV81RKIYGklf1GosviQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clYYR_iMGcNSMkR_QUR0sg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP_wWMWI36EIzs0HlfGGkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIia6sl5Ig-o6fd6bcRIeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ytNqmMNoCKBL8H64kooa6Q.png" /></figure><p>So fact 3 has been proved. There is a complex version of this match problem. It has more variables</p><p><strong>We have W workers and M machines, and each day, we can produce W*M candies. P candies are the cost to buy 1 machine/or hire 1 worker.<br> Find the minimum days to have N candies.</strong></p><p>The facts 1, 2, 3 can be proved similarly. There is an additional issue for this problem: When we buy/hire a machine/worker with all the candies we have, how do we decide to balance the machine/worker for maximum results?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFuX_9Y_x2gUXgkkKW-zOQ.png" /></figure><p>Here is the hacker rank link for this problem:</p><p><a href="https://www.hackerrank.com/challenges/making-candies/problem">https://www.hackerrank.com/challenges/making-candies/problem</a></p><p>I can’t solve this hard problem myself. After reading the discussion, I tried to prove the algorithm to solve this problem.</p><p>Here is the link for the solution <a href="https://www.hackerrank.com/challenges/making-candies/forum/comments/947633">https://www.hackerrank.com/challenges/making-candies/forum/comments/947633</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaa03941696d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Đầu tư tích luỹ trong thị trường cổ phiếu Việt Nam]]></title>
            <link>https://medium.com/@xuan11290/%C4%91%E1%BA%A7u-t%C6%B0-t%C3%ADch-lu%E1%BB%B9-trong-th%E1%BB%8B-tr%C6%B0%E1%BB%9Dng-c%E1%BB%95-phi%E1%BA%BFu-vi%E1%BB%87t-nam-3e9634ae7dd7?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e9634ae7dd7</guid>
            <category><![CDATA[vietnam]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[compound-interest]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Sun, 03 Sep 2023 07:29:48 GMT</pubDate>
            <atom:updated>2024-09-25T03:32:14.658Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>I/ Giới thiệu</strong></p><p>Có nhiều loại hình, phương pháp đầu tư phù hợp với mục tiêu, kỳ vọng và độ rủi ro mà nhà đầu tư có thể chấp nhận. Bất cứ 1 phương pháp nào cũng có những ưu, nhược điểm riêng. Về cơ bản, rủi ro cao thì tiềm năng lợi nhuận cao (đi đôi với tiềm năng mất tiền nhiều hơn). 1 số loại hình có thể kể đến ở Việt Nam như: cổ phiếu, trái phiếu, bất động sản, vàng, USD, v.v…</p><p>Gửi tiết kiệm là 1 kênh an toàn, và rủi ro thấp (nên lợi nhuận cũng sẽ thấp). Việc ngân hàng yếu kém bị phá sản thì chưa từng xảy ra ở Việt Nam, nhưng đã có 1 vài trường hợp được ngân hàng nhà nước mua lại để cải tổ hoạt động và tái cơ cấu, giúp ổn định an ninh tài chính, qua đó, bảo vệ quyền lợi cho người gửi, đồng thời, tạo động lực chung cho toàn bộ hệ thống ngân hàng thương mại.</p><p>Trong phạm vi của bài viết, mình chỉ tập trung vào vấn đề đầu tư tích luỹ hàng tháng đối với thị trường cổ phiếu, cụ thể mỗi tháng bạn dư 1 khoản tiền, thì cách thức thực hiện việc mua cổ phiếu như thế nào sẽ hiệu quả nhất.</p><p><strong>Kiến thức căn bản</strong></p><p>1 vài khái niệm cơ bản về tài chính các bạn có thể GG và tìm đọc ở các nguồn khác</p><ul><li>Các chỉ số tài chính quan trọng, quỹ ETF là gì, hoạt động như thế nào</li><li>Các loại lệnh chứng khoán: Phiên mở cửa, phiên đóng cửa, lệnh thị trường, giá đóng/mở cửa</li><li>Phân tích kỹ thuật, các chỉ báo kỹ thuật, trong bài viết mình sẽ sử dụng chỉ báo MACD</li></ul><p><strong>II/ Phân tích</strong></p><p>Mình lựa chọn cổ phiếu VCB như 1 ví dụ để mô phỏng việc thực hiện mua tích luỹ cổ phiếu này như thế nào thì hiệu quả nhất</p><p><strong>Tại sao lại là VCB?</strong></p><p>Nhóm VN30 là tập hợp của 30 cổ phiếu vốn hóa lớn, dựa trên bộ chỉ số do Sở Giao dịch Chứng khoán TP. HCM công bố, bắt đầu từ năm 2012.</p><p>Đây là phân bố tài sản của quỹ ETF <a href="https://dragoncapital.com.vn/cap-nhat-hoat-dong-quy-vfmvn30/">VFMVN30</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_r8IXsaMI_OzYPS6" /></figure><p>Ngân hàng chiếm khoảng 42%, mình ko có kiến thức để đánh giá con số này, điểm chính mình muốn đề cập là ngân hàng ở Việt Nam chiếm 1 tỷ trọng rất lớn trong quy mô của nền kinh tế.</p><p>Mình dự định sử dụng 1 quỹ ETF về ngân hàng để làm ví dụ, cụ thể là <a href="https://ssiam.com.vn/thong-tin-chung-ssiam-vnfin-lead">VNFINLEAD</a>, tuy nhiên quỹ này mới thành lập 24/2/2020 nên quy mô nhỏ và dữ liệu ko khách quan lắm. Và mình lựa chọn VCB làm ví dụ, là ngân hàng cũng như doanh nghiệp có vốn hoá lớn nhất trên sàn chứng khoán HOSE, niêm yết từ 2009.</p><p>Danh sách các <a href="https://vneconomy.vn/cac-etf-tai-viet-nam-bi-rut-rong-2-500-ty-dong-tu-dau-thang-8.htm">quỹ ETF ở Việt Nam</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ga1zI1dnL_lazORq" /></figure><p><strong>Dữ liệu phân tích là gì?</strong></p><p>VCB niêm yết vào t6/2009. Để làm tròn thì mình sẽ sử dụng khung thời gian 10 năm là từ 01/01/2013 -&gt; 31/12/2022</p><p>Với giả định mỗi tháng bạn đầu tư 10 triệu (10 năm là 1 tỷ 200 triệu, số tiền mang tính chất lấy ví dụ). Việc đầu tư đều đặn mỗi tháng sẽ sát với thực tế của nhà đầu tư cá nhân hơn là việc có 1 số tiền lớn và đầu tư ngay từ đầu</p><ul><li>Mình sẽ sử dụng giá mở cửa/đóng cửa trong ngày là giá trị để thực hiện mua cổ phiếu</li><li>Bỏ qua các vấn đề về làm tròn lô cổ phiếu (theo mình biết thì có lúc là lô 10, 100 và giờ có thể mua lô lẻ). Mình sẽ làm tròn xuống, ví dụ cp VCB có giá 11k thì 10tr sẽ mua ~ 909 cp</li><li>Về dữ liệu sử dụng thì các bạn có thể tự tìm các nguồn khác nhau, có 1 số dữ liệu có sẵn trên internet.</li></ul><p><strong>Bài viết này sẽ phân tích gì?</strong></p><p>Thị trường tốt, cổ phiếu tốt, nhưng ko có nghĩa là có thể mua bất cứ lúc nào. Với phương pháp đầu tư tích luỹ theo tháng, mình sẽ làm 1 phân tích chỉ rõ sự khác biệt về lợi nhuận kiếm được trong việc bạn chọn mua cổ phiếu vào thời điểm nào.</p><p><strong>1. Tích luỹ hàng tháng</strong></p><p>1 tháng có ~ 30 ngày, giả sử bạn ko tìm hiểu nhiều về vấn đề giá cp, chỉ đơn thuần áp dụng việc mua cổ phiếu định kỳ vào 1 ngày trong tháng. Liệu chọn mua định kỳ vào các ngày khác nhau trong tháng sẽ ảnh hưởng hiệu suất đầu tư như thế nào?</p><p>Mình sẽ sử dụng JAVA để demo cho các ý tưởng (do phần 2 mình có sử dụng 1 thư viện bên java để phân tích chỉ báo kỹ thuật)</p><pre>List&lt;Trading&gt; data = DbUtil.selectTrading(&quot;VCB&quot;,&quot;2010-01-01&quot;, &quot;2023-12-31&quot;);<br>DateFormat format = new SimpleDateFormat(&quot;yyyy-MM-dd&quot;, Locale.ENGLISH);<br>int quota = 10000000;<br>for (int day =1; day&lt;=30;day++){<br>   Long numberStock = 0L;<br>   for (int year = 2013;year&lt;=2022;year++){<br>       for (int month = 1;month&lt;=12;month++){<br>           String strDate = year+&quot;-&quot;+(month&lt;10 ? &quot;0&quot;+ month:month) + &quot;-&quot; + (day&lt;10 ? &quot;0&quot;+day:day);<br><br>           Date date = format.parse(strDate);<br>           Trading entryBuy = getFirstTradingFrom(data, date);<br>           double priceClose= entryBuy.getData().getDouble(&quot;priceClose&quot;);<br><br>           numberStock += Math.round(quota/(priceClose*(1+0.0015)));<br>       }<br>   }<br>   // price at 31-12-2022<br>   Trading targetPrice = getFirstTradingFrom(data, format.parse(&quot;2022-12-30&quot;));<br>   double profitPrice = targetPrice.getData().getDouble(&quot;priceClose&quot;);<br><br>   long moneySum = (long)(Math.round(profitPrice * 100.0) / 100.0)*numberStock;<br>   System.out.println(&quot;day: &quot;+day+ &quot; stocks: &quot;+numberStock+&quot; money: &quot;+(moneySum-0.0025*moneySum));<br>}</pre><ul><li>Ví dụ chọn ngày n (1–30) mà ko phải ngày thị trường hoạt động (ngày nghỉ, lễ tết), thì mình sẽ chọn ngày làm việc đầu tiên sau đó để mua.</li><li>Việc mua sẽ tốn 0.15% phí mua, khi bán sẽ tốn 0.15% phí bán + 0.1% thuế</li><li>Đầu tư 10 triệu mỗi tháng từ 01/01/2013 -&gt; 31/12/2022 (10 năm), và chốt lời vào ngày 30/12/2022</li></ul><p>Và đây là kết quả với cổ phiếu VCB:</p><pre>day: 1 stocks: 51005 money: 3.4463901257625E9<br>day: 2 stocks: 50889 money: 3.4385520460725E9<br>day: 3 stocks: 50913 money: 3.4401737177325E9<br>day: 4 stocks: 50849 money: 3.4358492599725E9<br>day: 5 stocks: 50728 money: 3.42767333202E9<br>day: 6 stocks: 50454 money: 3.409159247235E9<br>day: 7 stocks: 50452 money: 3.40902410793E9<br>day: 8 stocks: 50339 money: 3.4013887371975E9<br>day: 9 stocks: 50303 money: 3.3989562297075E9<br>day: 10 stocks: 50495 money: 3.4119296029875E9<br>day: 11 stocks: 50476 money: 3.41064577959E9<br>day: 12 stocks: 50513 money: 3.4131458567325E9<br>day: 13 stocks: 50559 money: 3.4162540607475E9<br>day: 14 stocks: 50480 money: 3.4109160582E9<br>day: 15 stocks: 50571 money: 3.4170648965775E9<br>day: 16 stocks: 50441 money: 3.4082808417525E9<br>day: 17 stocks: 50438 money: 3.408078132795E9<br>day: 18 stocks: 50356 money: 3.40253742129E9<br>day: 19 stocks: 50472 money: 3.41037550098E9<br>day: 20 stocks: 50318 money: 3.399969774495E9<br>day: 21 stocks: 50372 money: 3.40361853573E9<br>day: 22 stocks: 50412 money: 3.40632132183E9<br>day: 23 stocks: 50324 money: 3.40037519241E9<br>day: 24 stocks: 50371 money: 3.4035509660775E9<br>day: 25 stocks: 50383 money: 3.4043618019075E9<br>day: 26 stocks: 50482 money: 3.411051197505E9<br>day: 27 stocks: 50414 money: 3.406456461135E9<br>day: 28 stocks: 50298 money: 3.398618381445E9<br>day: 29 stocks: 50301 money: 3.3988210904025E9<br>day: 30 stocks: 50211 money: 3.3927398216775E9</pre><p>Sai khác giữa ngày nhiều nhất (ngày 1: 3.446 tr) và ngày ít nhất (ngày 30: 3.392 tr) là ~ 54 tr.<br>Số tiền này chỉ ~ 1.6% sai lệch (trong 30 ngày được chọn), tuy nhiên nếu tính trên tổng số tiền bỏ ra 10 năm là 1 tỷ 2 thì ~ 4.5%, và so với số tiền 10tr bỏ ra hàng tháng thì là khá lớn.</p><p>Tiếp tục với <strong>BID</strong> là ngân hàng nhà nước với vốn hoá đứng thứ 2, niêm yết năm 2014. Mình lấy số liệu từ 01/01/2015 -&gt; 31/12/2022.</p><p>Ngày nhiều nhất (ngày 1: 1.850 tr) và ngày ít nhất (ngày 29: 1.816 tr), sai khác: 34tr. Sai lệch 1.9%. Trên tổng số tiền bỏ ra 8 năm 960tr thì ~3.5%</p><p>Mình sẽ lấy thêm ví dụ về 1 ngân hàng (ko phải nhà nước) là <strong>MBB</strong> (<strong>TCB</strong> niêm yết giữa 2018, thời gian còn ngắn nên mình ko sử dụng), cũng đã niêm yết hơn 10 năm. Mốc số liệu từ 01/01/2013 -&gt; 31/12/2022</p><p>Ngày nhiều nhất (ngày 1, ngày 3: 2.935) và ngày ít nhất (ngày 30: 2.897 tr), sai khác: 38tr. Sai lệch 1.3%. Trên tổng số tiền bỏ ra 10 năm 1tỷ 2 thì ~3.1%</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLMD3ZBli5pfG82jL9uUmA.png" /></figure><p><strong>Đối với 1 vài ngân hàng có vốn hoá lớn và niêm yết trong thời gian dài, việc lựa chọn vào ngày đầu tiên của tháng cho việc đầu tư tích luỹ có vẻ là 1 lựa chọn tốt khi đem lại lợi nhuận lớn nhất.</strong></p><p><strong>Vậy có lý giải gì cho pattern này ko? </strong><br>Có thể là ngày đầu tháng các nhà đầu tư còn đang khởi động chưa mua nhiều như các ngày khác trong tháng, nên mua ở đầu tháng trong dài hạn sẽ có giá rẻ hơn so với các ngày khác. Mình cũng ko có lời giải thích thoả đáng, cũng có thể chỉ là yếu tố ngẫu nhiên.</p><p>Pattern này làm mình nhớ tới cuốn sách OUTLIERS của tác giả Malcolm Gladwell, trong đó có 1 chương tác giả giải thích lý do tại sao các cầu thủ khúc côn cầu chuyên nghiệp tại Canada có ngày sinh thuộc nửa đầu năm hơn là nửa cuối. Tưởng như là ngẫu nhiên nhưng lại ko phải vậy.</p><p>Quay trở lại cổ phiếu VCB, mỗi tháng đầu tư 10tr vào ngày 1 đầu tháng, trong 10 năm từ ngày 01/01/2013 -&gt; 31/12/2022, chốt lời dùng giá đóng cửa ngày 30/12/2022, thu về khoản tiền ~ 3.446 tr (3 tỷ 446 triệu).</p><p>Bạn có thể sử dụng công cụ tính toán <a href="https://vietnamsalary.careerbuilder.vn/tinh-lai-kep.html?orgMoney=0&amp;moneyPerMonth=10000000&amp;numberOfYears=10&amp;rate=+22&amp;period=1">lãi kép online này</a>, thì nó <strong>tương đương với lãi suất ~</strong> <strong>22%/1 năm liên tục trong 10 năm</strong>. 1 con số hết sức ấn tượng.</p><p><strong>Vậy nếu lựa chọn ngẫu nhiên thì mức lãi sẽ như thế nào?</strong></p><p>Để tính trường hợp tệ nhất/tốt nhất có thể xảy ra, thì nó tương ứng với việc bạn chọn mức giá cao nhất/thấp nhất trong tháng để mua tích luỹ. Với cổ phiếu VCB thì con số sẽ là:</p><p>Tốt nhất: stocks: 53376 money: 3.60659777184E9</p><p>Tệ nhất: stocks: 47929 money: 3.2385458746725E9</p><p>Chọn ngày 1: stocks: 51005 money: 3.4463901257625E9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMA8CwJYrvCnTJxrkrkB1w.png" /></figure><p>Trường hợp tốt nhất hơn 11% so với tệ nhất, 1 con số đáng kể. Tuy nhiên bạn ko cần quá lo lắng, vì nếu chỉ ngẫu nhiên lựa chọn tuỳ ý, thì xác suất để rơi vào trường hợp tệ nhất (hoặc tốt nhất) là (1/30)¹²⁰=5.56E-178. Cực kỳ nhỏ.</p><p>Lãi suất 22%/1 năm trong 10 năm liên tục là mặt tích cực của vấn đề, với việc đầu tư tích luỹ trong thị trường cổ phiếu, cũng cần liệt kê các mặt bi quan như sau</p><ul><li>Làm sao bạn có thể lựa chọn cổ phiếu như VCB hay MBB để đạt được mức lãi suất như vậy. Đâu là ngành nghề sẽ phát triển trong 10 năm tới, hoặc công ty nào là công ty đi đầu trong ngành nghề đó? Bỏ qua vấn đề chia cổ tức hoặc cổ phiếu, thì cổ phiếu VCB trong khoảng thời gian 10 năm phân tích tăng giá 6.5 lần (1 con số khủng khiếp nếu tính riêng về hiệu quả đầu tư) (1)</li><li>Pattern chọn vào ngày 1 của tháng chỉ là 1 pattern với 1 vài cổ phiếu lớn, niêm yết lâu năm ngành ngân hàng. Tuỳ mỗi ngành nghề, mỗi công ty sẽ có những biểu đồ giá khác nhau.</li><li>Việc phân tích là dựa trên dữ liệu lịch sử, đúng cho 10 năm trước ko có nghĩa là 1 năm tới, hoặc 10 năm tới pattern đó cũng sẽ đúng. Người ta hay nói là: Chứng khoán ko nói chuyện quá khứ là như vậy. Và hơn hết, khi 1 thông tin được khai thác quá nhiều, nó sẽ ko còn giá trị nữa. Ví dụ rất nhiều người mua vào ngày 1 thì nó sẽ ko còn đúng nữa.</li><li>Nên nhớ việc đầu tư tích luỹ là việc làm trong dài hạn (ở đây là 10 năm), mình lấy 1 mẫu sample khác là trong 3 năm (01/01/2020 -&gt; 31/12/2022), là quãng thời gian khó khăn với thị trường chung cũng như là VCB, với cùng bài toán là đầu tư 10 triệu 1 tháng vào ngày 1. Thì số tiền thu về là: 397tr, trên số tiền bỏ ra là 360tr. Tức là chỉ ~10% sau 3 năm đầu tư trên tổng vốn (bỏ qua vấn đề chia cổ tức và cổ phiếu)</li></ul><p>Với câu hỏi số (1), với 1 người ko có kiến thức tài chính cũng như ko có nhiều thời gian theo dõi thị trường, vẫn dành phần lớn thời gian làm việc trong lĩnh vực khác thì chọn quỹ ETF là 1 lựa chọn có vẻ phù hợp hơn cả.</p><p>Lấy ví dụ 1 vài quỹ ETF trong nước mà có thể dễ dàng mua bán thông qua các công ty chứng khoán</p><p><a href="https://dragoncapital.com.vn/quy-etf-vfmvn-diamond/etf-ket-qua-hoat-dong/"><strong>E1VFVN30</strong></a> Thành lập từ 14/08/2014, hiệu suất từ khi thành lập: 111%</p><p><a href="https://dragoncapital.com.vn/quy-etf-vfmvn-diamond/etf-ket-qua-hoat-dong/"><strong>FUEVFVND</strong></a><strong> </strong>Thành lập từ 22/04/2020, hiệu suất từ khi thành lập: 166%</p><p><a href="https://ssiam.com.vn/thong-tin-chung-ssiam-vnfin-lead"><strong>FUESSVFL</strong></a> Thành lập từ 24/02/2020, hiệu suất từ khi thành lập: 95%</p><p>Việc bán đỉnh/mua đáy gần như là không thể (với xác suất ~ 0% mình liệt kê ở trên), vậy có những phương pháp nào để mua gần đáy, hoặc bán gần đỉnh trong 1 vài điều kiện nhất định ko?. Mình sẽ dùng phân tích kỹ thuật để demo cách tiếp cận này.</p><p><strong>2. Dựa vào đồ thị giá để tìm điểm mua thích hợp</strong></p><p><a href="https://github.com/ta4j/ta4j">TA4j</a> là 1 thư viện khá phổ biến trong JAVA cho việc phân tích kỹ thuật, mình sẽ sử dụng thư viện này để thực hiện việc demo. Có 1 chỉ báo khá quen thuộc trong việc xác định điểm mua/bán là MACD, mình ko giải thích chi tiết về chỉ báo này trong bài viết vì có rất nhiều thông tin trên internet về nó.( <a href="https://www.investopedia.com/terms/m/macd.asp">các chỉ báo kỹ thuật</a>)</p><p>Về cơ bản đây là 1 chỉ báo mạnh khi thị trường có xu hướng rõ ràng (tăng hoặc giảm), còn khi thị trường đi ngang, thì chỉ báo này sẽ đưa ra nhiều tín hiệu mua/bán nhiễu ko hiệu quả.</p><p>Do mình chỉ có data với khung thời gian là theo ngày, nên sẽ tạo BarSeries với khung thời gian là theo ngày.</p><pre>private static void createBarSeries<br>(BarSeries series, ZonedDateTime beginTime, ZonedDateTime endTime, int duration,<br>                               List&lt;Trading&gt; data) {<br>   Duration barDuration = Duration.ofSeconds(duration);<br>   ZonedDateTime barEndTime = beginTime;<br>   int i = 0;<br>   do {<br>       barEndTime = barEndTime.plus(barDuration);<br>       Bar bar = new BaseBar(barDuration, barEndTime, series.function());<br>       do {<br>           Trading item = data.get(i);<br>           ZonedDateTime tradeTimeStamp = ZonedDateTime<br>                   .ofInstant(Instant.ofEpochMilli(item.getTimeStamp()), ZoneId.systemDefault());<br>           // if the trade happened during the bar<br>           if (bar.inPeriod(tradeTimeStamp)) {<br>               double tradePrice = item.getData().getDouble(&quot;priceClose&quot;);<br>               double tradeVolume = item.getData().getDouble(&quot;volume&quot;);<br>               bar.addTrade(tradeVolume, tradePrice, series.function());<br>           } else {<br>               // the trade happened after the end of the bar<br>               // go to the next bar but stay with the same trade (don&#39;t increment i)<br>               // this break will drop us after the inner &quot;while&quot;, skipping the increment<br>               break;<br>           }<br>           i++;<br>       } while (i &lt; data.size());<br>       // if the bar has any trades add it to the bars list<br>       // this is where the break drops to<br>       if (bar.getTrades() &gt; 0) {<br>           series.addBar(bar);<br>       }<br>   } while (barEndTime.isBefore(endTime));<br>}</pre><p>Tạo chiến lược giao dịch với MACD</p><pre>public static Strategy buildMACD(BarSeries series, MACDFactor factor) {<br>   if (series == null) {<br>       throw new IllegalArgumentException(&quot;Series cannot be null&quot;);<br>   }<br><br>   ClosePriceIndicator closePrice = new ClosePriceIndicator(series);<br>   MACDIndicator macd = new MACDIndicator(closePrice, factor.shortBarCount, factor.longBarCount);<br>   EMAIndicator emaMacd = new EMAIndicator(macd, factor.signalBarCount);<br><br>   Rule entryRule = new OverIndicatorRule(macd, emaMacd);<br>   Rule exitRule = new UnderIndicatorRule(macd, emaMacd);<br>   return new BaseStrategy(entryRule, exitRule);<br>}</pre><p>Chạy chiến lược MACD trên bộ barSeries vừa được tạo</p><pre>BarSeries series = createBarSeries(item, startTime, endTime);<br>Strategy strategy = buildMACD(series, standardFactor);<br>BarSeriesManager seriesManager = new BarSeriesManager(series);<br>TradingRecord tradingRecord = seriesManager.run(strategy);</pre><p>Để đơn giản thì mình bỏ qua vấn đề <a href="https://support.vndirect.com.vn/hc/vi/articles/9816355920153-Chu-k%E1%BB%B3-thanh-to%C3%A1n-ch%E1%BB%A9ng-kho%C3%A1n">T+ ở thị trường Việt Nam</a>, hiểu đơn giản thì mua cổ phiếu sau ~2 ngày mới nắm giữ thực sự để có thể bán, bán cổ phiếu thì cũng ~ 2 ngày tiền mới về để mua tiếp.</p><p>Mình sẽ lấy 1 ví dụ cụ thể trong khung thời gian từ 01/01/2020 -&gt; 31/12/2020 của mã cổ phiếu VCB để so sánh (như nói từ đầu về chỉ báo MACD, nó cần những điều kiện nhất định để có thể hiệu quả trong việc cố gắng mua gần đáy, bán gần đỉnh. Có 1 pha sập mạnh/hồi mạnh của giá cp VCB trong giai đoạn này)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-iZzt6q7vMpp5_zB" /></figure><p>Giả sử bạn có 120tr tiền vốn.</p><p><strong>TH1:</strong></p><p>Bạn mua cổ phiếu VCB vào ngày 01/01/2020 (ngày 02/01/2020 mới làm việc), với giá là: 59.041 1cp. Chốt lời ngày 30/12/2020 với giá là: 64.177 1cp. Lời ~ 8%. <br>Ở đây để đơn giản mình bỏ qua các vấn đề về chia cổ tức, hoặc chia cổ phiếu (đây là các yếu tố có a/h tới giá cổ phiếu + số lượng cổ phiếu bạn nắm giữ)</p><p><strong>TH2:</strong></p><p>Áp dụng chỉ báo MACD để tìm các điểm mua, điểm bán.</p><p><strong>Với bộ chỉ số MACD cơ bản</strong>: shortBarCount=12, longBarCount=26, signalBarCount=9</p><p>Theo <a href="https://en.wikipedia.org/wiki/MACD">wikipedia</a>, chỉ số này được phát minh bởi Gerald Appel những năm 1970. Nó phù hợp với thị trường Mỹ tại thời điểm đó. Với thị trường Việt Nam, và với 1 cổ phiếu cụ thể, nó ko hẳn đã là 1 bộ chỉ số tốt.</p><p>Ý tưởng về hàm tính lợi nhuận:</p><ul><li>Với 120 triệu, mỗi lần mua/bán mình sẽ thực hiện mua hết số tiền có/ bán hết số cp nắm giữ</li><li>Vẫn có tính phí mua, phí bán và thuế.</li></ul><pre>public static double profitFix(TradingRecord tradingRecord, double startMoney){<br>   double totalMoney=startMoney;<br>   for (int i=0;i&lt;tradingRecord.getTrades().size();i++){<br>       Trade trade = tradingRecord.getTrades().get(i);<br><br>       Order buyOrder = trade.getEntry();<br>       long numberStocks = Math.round(totalMoney/(buyOrder.getNetPrice().doubleValue()*(1+0.0015)));<br><br>       Order exitOrder = trade.getExit();<br>       double sellStockMoney = numberStocks * exitOrder.getNetPrice().doubleValue();<br>       totalMoney = sellStockMoney - 0.0015*sellStockMoney - 0.001*sellStockMoney;<br>   }<br><br>   return totalMoney;<br>}</pre><p>Kết quả:</p><p>VCB_tradeCount:8_profit:154988751_macd(12,26,9)</p><p>MACD(12,26,9) khuyến nghị 8 lần giao dịch (1 giao dich = 1 lần mua + 1 lần bán), thu về lợi nhuận là 154.988.751 ~ Lời 29%</p><p><strong>Bộ số MACD nào là tốt nhất</strong></p><p>Mình thực hiện việc quét tất cả các trường hợp của bộ 3 chỉ số này, với ràng buộc:<br>1&lt;=shortBarCount,longBarCount,signalBarCount&lt;=30, shortBarCount&lt;longBarCount.</p><p>Kết quả bộ số tốt nhất:</p><p>VCB_tradeCount:13_profit:178269029_macd(3,22,6)</p><p>MACD(3,22,6) khuyến nghị 13 lần giao dịch, thu về lợi nhuận là 178.269.029 ~ Lời 48%</p><p><strong>TH3:</strong></p><p>Trường hợp này chỉ mang tính giả định và ko sát thực tế, tức là 120 triệu sẽ được giữ và đầu tư dần mỗi tháng 10 triệu vào ngày 1 của tháng (tức là om vốn để đầu tư dần), thì trong khoảng thời gian 01/01/2020 -&gt; 31/12/2020, sẽ đạt lợi nhuận như thế nào?</p><p>Kết quả là:<br>day: 1 stocks: 2265 money: 1.530452629125E8</p><p>~ Lời 27%, gần tương đương với việc sử dụng MACD với bộ chỉ số cơ bản.</p><p>=&gt; Việc đầu tư tích luỹ hàng tháng về cơ bản cũng sẽ tận dụng khá tốt quãng thời gian mà cổ phiếu sụt giá và sau đó tăng giá trở lại.</p><p><strong>TH4:</strong></p><p>Nếu vẫn đầu tư tích luỹ, tuy nhiên kết hợp chỉ báo MACD để tìm điểm mua/bán thì sẽ như thế nào?</p><ul><li>Có thêm 10 triệu mỗi tháng (vào ngày 1) để cộng dồn đầu tư thêm khi mua</li><li>Trong quá trình đợi tìm điểm vào phù hợp MACD, số tiền nhàn rỗi vẫn có thể để sinh lời khi gửi tiết kiệm với khung thời gian nhỏ (tuy nhiên mình sẽ bỏ qua phần lợi nhuận này)</li></ul><pre>   public static double profitStock(TradingRecord tradingRecord, List&lt;Trading&gt; data, Long startTime){<br>       int savePerMonth = 10000000; // 10tr<br>       double totalSave=0f;<br>       for (int i=0;i&lt;tradingRecord.getTrades().size();i++){<br>           Trade trade = tradingRecord.getTrades().get(i);<br>           Order buyOrder = trade.getEntry();<br>           Long current = data.get(buyOrder.getIndex()).getTimeStamp();<br>           Long lastExist = 0l;<br>           if (i==0) {<br>               lastExist = startTime;<br>           }else{<br>               lastExist = data.get(tradingRecord.getTrades().get(i-1).getEntry().getIndex()).getTimeStamp();<br>           }<br><br>           int monthSaveMore = countDayOneOfMonths(lastExist, current);<br>           double moneyHave = totalSave + savePerMonth*monthSaveMore;<br>           long numberStocks = Math.round(moneyHave/(buyOrder.getNetPrice().doubleValue()*(1+0.0015)));<br><br>           Order exitOrder = trade.getExit();<br>           double sellStockMoney = numberStocks * exitOrder.getNetPrice().doubleValue();<br>           totalSave = sellStockMoney - 0.0015*sellStockMoney - 0.001*sellStockMoney;<br>       }<br>       return totalSave;<br>   }<br><br>public static int countDayOneOfMonths(Long startTime, Long endTime) {<br>   int count = 0;<br>   Calendar cal = Calendar.getInstance();<br>   cal.setTimeInMillis(startTime);<br><br>   while(cal.getTimeInMillis()&lt;endTime){<br>       if (cal.get(Calendar.DAY_OF_MONTH)==1)count++;<br><br>       cal.add(Calendar.DATE,1);<br>   }<br><br>   return count;<br>}</pre><p>Ta có kết quả cho MACD với bộ chỉ số cơ bản và bộ chỉ số tốt nhất như sau:</p><p>VCB_tradeCount:8_profit:138284903_macd(12,26,9)</p><p>VCB_tradeCount:13_profit:150747230_macd(3,22,6)</p><p>TH4 này tệ hơn so với TH2 vì cùng 1 phương pháp và điểm mua/bán, tuy nhiên TH2 có vốn lớn từ đầu, còn TH4 vốn tích luỹ dần hàng tháng.</p><p>Ta có bảng sau: Với vốn 120 triệu, đầu tư cổ phiếu VCB trong khoảng thời gian 01/01/2020 -&gt; 31/12/2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gprioZSqn34lLcXtglKgXg.png" /></figure><p>Các khoản lời % trong 1 năm là rất hứa hẹn, tuy nhiên cũng cần phân tích các vấn đề sau</p><ul><li>Việc áp dụng MACD chỉ tốt khi xảy ra biến động mạnh về giá (lên/xuống). Ko thể biết đâu là đỉnh, tuy nhiên sau khi cổ phiếu giảm giá mạnh, đây là 1 chỉ báo khá hữu ích để tìm điểm mua hợp lý (sau sự kiện giá giảm mạnh)</li><li>Việc các vị thế tốt xuất hiện (khi áp dụng các chỉ báo kỹ thuật) là thường ít khi xảy ra (ví dụ 95% luôn ở dạng 50/50 ko rõ ràng về tín hiệu, 5% là rõ vị thế để vào). Lấy trường hợp MACD trên làm ví dụ, trong 1 năm có 250 ngày giao dịch, chỉ có 8 ngày là MACD khuyến nghị mở vị thế mua ~ 3%. Nếu ko có các công cụ máy tính hỗ trợ, việc sử dụng chỉ báo kỹ thuật cho việc mua/bán thủ công là rất mất thời gian và tốn kém. (Chưa kể bạn muốn cùng lúc theo dõi 30 cổ phiếu trong rổ VN30 chẳng hạn)</li><li>Về vấn đề bộ chỉ số tối ưu cho MACD. Bộ chỉ số này là tối ưu với 1 khung thời gian (tương đương với 1 dạng đồ thị cụ thể), nó sẽ ko còn là bộ số tốt nhất với dạng đồ thị khác (hoặc khung thời gian khác). Việc tìm bộ số tối ưu hơn ở đây chỉ ra việc nên hiểu bản chất chỉ số, và tuỳ hoàn cảnh, điều kiện để có được bộ chỉ số với tín hiệu mua bán tốt nhất.</li><li>MACD ko phù hợp để sử dụng cùng với việc tích luỹ hàng tháng (kể cả việc xảy ra điều kiện lên/xuống mạnh về giá). Để minh hoạ cho vấn đề này, mình sử dụng hàm profitStock bên trên nhưng cho khung thời gian 10 năm, từ 01/01/2013 -&gt; 31/12/2022. Kết quả là:</li></ul><p>VCB_tradeCount:91_profit:1927015856_macd(12,26,9): Giao dịch 91 lần trong 10 năm (mỗi tháng 10 triệu là vốn 1 tỷ 200 triệu), thu về 1 tỷ 927 triệu</p><p>VCB_tradeCount:46_profit:3164103784_macd(16,29,26): Bộ chỉ số tốt nhất 10 năm, giao dịch 46 lần, thu về 3 tỷ 164 triệu</p><p>Chú ý rằng nếu chỉ dùng đầu tư tích luỹ hàng tháng 10tr vào ngày 1, trong 10 năm, thì số tiền thu về là: 3 tỷ 446 triệu</p><p><strong>III/ Kết luận</strong></p><p>Lãi suất kép là kỳ quan thứ 8 của thế giới — <strong>Albert Einstein</strong></p><p>Việc đầu tư tích luỹ 1 cách kiên định, kỷ luật đối với 1 cổ phiếu tăng trưởng trong thời gian dài đem tới 1 lợi ích ko thể bàn cãi. Tuy nhiên sẽ là thảm hoạ nếu bạn lựa chọn 1 cổ phiếu, hoặc 1 quỹ (chỉ số) ko tăng trưởng, thậm chí là lỗ và phá sản. Hãy tìm hiểu kỹ về vấn đề cổ phiếu tốt, hay với 1 người ko có nhiều kiến thức về tài chính như mình, những quỹ ETF lớn của các tổ chức uy tín là 1 lựa chọn phù hợp, an toàn với kỳ vọng sinh lời vừa phải.</p><p>Chỉ báo kỹ thuật bản chất là các công thức toán học cho thấy các xu hướng chuyển động của giá, việc hiểu bản chất của từng chỉ báo sẽ giúp sử dụng đúng đắn và tối ưu hiệu suất. Khi thị trường có những pha giảm sâu, hãy nhớ tới MACD như 1 chỉ báo hỗ trợ việc tìm điểm mua phù hợp (trong ngữ cảnh bạn muốn đầu tư 1 khoản tiền lớn trong 1 khoảng thời gian ngắn, ko dành cho nhu cầu tích luỹ)</p><p><strong>Tài liệu tham chiếu</strong></p><p>1. Về đầu tư giá trị, có 1 website ở VN mình đánh giá cao, kiến thức phù hợp với người chưa có nền tảng về tài chính</p><p><a href="https://govalue.vn/">https://govalue.vn</a></p><p>2. Về các chỉ báo phân tích kỹ thuật</p><p><a href="https://www.investopedia.com/technical-analysis-4689657">https://www.investopedia.com/technical-analysis-4689657</a></p><p>Thư viện Ta4j trong java: <a href="https://github.com/ta4j/ta4j">https://github.com/ta4j/ta4j</a></p><p>3. Có 1 trường phái là đầu tư theo tin, có 1 cuốn sách khá hay mà mình muốn giới thiệu về câu chuyện đầu tư nội gián</p><p><a href="https://tiki.vn/loi-the-den-p2916515.html">https://tiki.vn/loi-the-den-p2916515.html</a></p><p>Có 1 series phim có thể nói cũng có nhiều ý tưởng từ cuốn sách: <a href="https://www.imdb.com/title/tt4270492/">https://www.imdb.com/title/tt4270492/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e9634ae7dd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synchronization in GO (part 1)]]></title>
            <link>https://medium.com/@xuan11290/synchronization-in-go-part-1-be36e1e36411?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/be36e1e36411</guid>
            <category><![CDATA[atomic]]></category>
            <category><![CDATA[memory-model]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-mutex]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 15:44:55 GMT</pubDate>
            <atom:updated>2023-08-16T15:44:55.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*Tb9jiZA2oawcY43f" /></figure><h3><strong>I/ Introduction</strong></h3><p>Synchronization is a crucial concept in concurrent and parallel programming, as it deals with the coordination of multiple threads or goroutines to ensure safe access to shared resources and correct program execution. Synchronization techniques help prevent race conditions, deadlocks, and other concurrency-related issues. In this article, we will focus on synchronization in the Go programming language, which provides channels, mutexes, and the sync package for managing concurrent access to resources.</p><p><strong>Channels: A Core Concept in Go</strong></p><p>Channels are the primary means of synchronization and communication between goroutines in Go. They provide a simple and efficient way to pass data between goroutines, ensuring that the data is neither accessed nor modified simultaneously. Channels can be thought of as pipes that connect concurrent goroutines, allowing them to send values of a specific type.</p><p>Channels can be buffered or unbuffered. Unbuffered channels block the sender until the receiver is ready to receive the data, while buffered channels use a buffer to store the data until the receiver is ready, allowing the sender to continue without waiting.</p><p><strong>Mutexes: Safeguarding Shared Resources</strong></p><p>Mutexes (short for “mutual exclusion”) are used to protect shared resources from concurrent access. In Go, the <strong><em>sync.Mutex</em></strong> type provides basic Mutex functionality, with lock and unlock methods to control access to a critical section of code.</p><p>A mutex can be used to lock shared resources, ensuring that only one goroutine can access them at a time. When a goroutine acquires the lock on a mutex, other goroutines attempting to access the same resource are blocked until the lock is released.</p><p>It is essential to ensure that the mutex is unlocked after the critical section, even in case of a panic or error.</p><p><strong>Sync Package: Additional Synchronization Utilities</strong></p><p>The <strong><em>sync</em></strong> package in Go provides additional synchronization primitives, including WaitGroup, Cond, and Once.</p><p>The <strong><em>sync/atomic</em></strong> package is part of the Go standard library and provides a set of low-level atomic memory operations for synchronization purposes. These atomic operations allow you to perform basic read, write, and arithmetic operations on shared variables in a concurrent-safe manner without requiring locks or mutexes. <strong><em>Atomic operations are designed to be fast and efficient, but they should be used with care, as they can be more challenging to reason about compared to higher-level synchronization constructs like channels and mutexes.</em></strong></p><p>While atomic operations provide a fast and efficient way to perform basic synchronization tasks, they come with certain limitations and challenges:</p><ul><li><strong>Limited operations</strong>: Atomic operations only support basic integer and pointer types and a limited set of operations. For more complex synchronization tasks, channels or mutexes should be used instead.</li><li><strong>Harder to reason about:</strong> Atomic operations can be more difficult to reason about, as they require a deep understanding of memory ordering and the hardware memory model. This can lead to subtle and hard-to-detect bugs.</li><li><strong>Less expressive:</strong> Atomic operations can be less expressive compared to channels and mutexes, making it harder to model complex synchronization scenarios.</li></ul><p>Despite these limitations, atomic operations can be a powerful tool when used correctly. They are particularly useful in performance-critical sections of code where minimizing locking overhead is essential. However, developers should carefully consider whether the benefits of using atomic operations outweigh the risks and complexity associated with them.</p><p><strong>In this part 1, I will try to explain some fundamental concepts and do a basic experiment using Go synchronization, comparing several ways to do a simple task and trying to reason about it.</strong></p><h3><strong>II/ Memory models</strong></h3><p>To understand and use sync/atomic correctly, we need to understand memory models.</p><p>A memory model, also known as a memory consistency model, is a specification that describes the behavior of shared memory in a concurrent or parallel system. It defines the rules for how memory operations, such as reads and writes, are ordered and when their effects become visible to other threads or processors. Memory models are essential for understanding and reasoning about the behavior of concurrent programs, as they help to ensure program correctness and avoid synchronization-related bugs, such as race conditions.</p><p><strong>Why Memory Models Matter</strong></p><p>In modern computer systems, various factors can influence the order in which memory operations are executed and when their results become visible to other threads or processors. These factors include compiler optimizations, CPU out-of-order execution, and cache hierarchies. As a result, the order in which memory operations appear in the program code may not always match the order in which they are executed at runtime.</p><p>Memory models define a set of rules and guarantees that allow developers to reason about the behavior of shared memory in concurrent systems. They help to ensure that programs behave as expected, even when memory operations are reordered or optimized at runtime. By understanding the memory model of a programming language or system, developers can write correct and efficient concurrent code without introducing subtle and hard-to-diagnose bugs.</p><p><strong>Memory Models in Programming Languages</strong></p><p>Different programming languages and systems have different memory models. Some languages, like C++ and Java, provide a well-defined memory model as part of their language specification. These memory models define the rules for how memory operations are ordered and when their results become visible to other threads in a portable and language-agnostic way.</p><p>In the context of the Go programming language, the memory model is specified in the <a href="https://golang.org/ref/mem">Go Memory Model document</a>. The Go memory model is intentionally kept simple, focusing on providing a set of basic guarantees that developers can rely on when writing concurrent code. The key guarantees provided by the Go memory model include:</p><ul><li><strong>Sequential consistency</strong>: Within a single goroutine, the order of memory operations is guaranteed to be the same as the order in which they appear in the program code.</li><li><strong>Happens-before relationship</strong>: Certain operations, such as the send and receive operations on channels, establish a happens-before relationship between memory operations. If operation A happens-before operation B, then the effects of A are guaranteed to be visible to B.</li><li><strong>No guarantee without synchronization</strong>: In the absence of explicit synchronization, such as channels or sync primitives (mutexes, atomic operations, etc.), there is no guarantee on the order in which memory operations become visible to other goroutines.</li></ul><p>These guarantees help developers reason about the behavior of their concurrent code and ensure that it behaves correctly even when memory operations are reordered or optimized at runtime.</p><p>I just try to recap the memory model in summary, but for detailed information, I strongly recommend reading 2 posts from Google team</p><h4><a href="https://research.swtch.com/hwmm">Hardware memory models</a></h4><h4><a href="https://research.swtch.com/plmm">Programming language memory models</a></h4><h3><strong>III/ Benchmark and analysis</strong></h3><p>As mentioned above, we have 3 ways to use Go synchronization. There are a lot of scenarios, so I just take a simple example to understand the difference at a basic level.</p><ul><li>Comparing methods: channel, mutex, sync/atomic</li><li>Concurrent read/write on a simple counter (with separating scenarios at some specific read/write rate)</li></ul><p><strong>For sync/atomic</strong>.</p><p>We use load/store atomic operation to make a simple counter</p><pre>type AtomicCounter struct {<br>  counter int64<br>}<br><br>func (c *AtomicCounter) Inc() {<br>  atomic.AddInt64(&amp;c.counter, 1)<br>}<br><br>func (c *AtomicCounter) Load() int64 {<br>  return atomic.LoadInt64(&amp;c.counter)<br>}</pre><p><strong>For mutex.</strong></p><pre>type MutexCounter struct {<br>  counter int64<br>  lock    sync.RWMutex<br>}<br><br>func (c *MutexCounter) Inc() {<br>  c.lock.Lock()<br>  defer c.lock.Unlock()<br><br>  c.counter++<br>}<br><br>func (c *MutexCounter) Load() int64 {<br>  c.lock.RLock()<br>  defer c.lock.RUnlock()<br><br>  return c.counter<br>}</pre><p>Take a look at how mutex is implemented in GO language</p><p><a href="https://github.com/golang/go/blob/master/src/sync/mutex.go">https://github.com/golang/go/blob/master/src/sync/mutex.go</a></p><p>There are 2 things that need to be noticed here</p><ul><li>It uses a for loop with an atomic operation: CAS (compare and swap) until it succeeds. (CAS is a key technique in lock-free programming)</li><li>It has a lock mechanism to avoid starvation. For example: If there are a lot of reading locks, how do you make sure that the write lock is acquired to update the data?</li></ul><p><strong>For channel.</strong></p><pre>type ChannelCounter struct {<br> counter int64<br> lock    ChLock<br>}<br><br>func (c *ChannelCounter) Inc() {<br> c.lock.Lock()<br> defer c.lock.Unlock()<br><br> c.counter++<br>}<br><br>func (c *ChannelCounter) Load() int64 {<br> c.lock.Lock()<br> defer c.lock.Unlock()<br><br> return c.counter<br>}<br><br>type ChLock chan struct{}<br><br>func NewChLock() ChLock {<br> return make(chan struct{}, 1)<br>}<br><br>func (l ChLock) Lock()   { l &lt;- struct{}{} }<br>func (l ChLock) Unlock() { &lt;-l }</pre><p>The read/write rate is a critical factor in performance. That is why I try to add a control r/w rate to the benchmark.</p><p>Here is the code for the benchmark, note that the random function will impact our result, so I did a separating benchmark for using this function, then will decrease this cost later in the final result.</p><pre>var percent = 9<br><br>func Benchmark_Random(b *testing.B) {<br>  b.RunParallel(func(pb *testing.PB) {<br>     for pb.Next() {<br>        rnd := rand.Intn(10)<br>        if rnd &lt; percent {<br>        } else {<br>        }<br>     }<br>  })<br>}<br><br>func Benchmark_AtomicCounter(b *testing.B) {<br>  counter := AtomicCounter{}<br>  b.RunParallel(func(pb *testing.PB) {<br>     for pb.Next() {<br>        rnd := rand.Intn(10)<br>        if rnd &lt; percent {<br>           counter.Inc()<br>        } else {<br>           counter.Load()<br>        }<br>     }<br>  })<br>}<br><br>func Benchmark_MutexCounter(b *testing.B) {<br>  counter := MutexCounter{}<br>  b.RunParallel(func(pb *testing.PB) {<br>     for pb.Next() {<br>        rnd := rand.Intn(10)<br>        if rnd &lt; percent {<br>           counter.Inc()<br>        } else {<br>           counter.Load()<br>        }<br>     }<br>  })<br>}<br><br>func Benchmark_ChannelCounter(b *testing.B) {<br>  counter := ChannelCounter{lock: NewCLock()}<br>  b.RunParallel(func(pb *testing.PB) {<br>     for pb.Next() {<br>        rnd := rand.Intn(10)<br>        if rnd &lt; percent {<br>           counter.Inc()<br>        } else {<br>           counter.Load()<br>        }<br>     }<br>  })<br>}</pre><p>My laptop environment</p><pre>goos: darwin<br>goarch: amd64<br>pkg: test<br>cpu: Intel(R) Core(TM) i7–9750H CPU @ 2.60GHz</pre><p>Here is the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rRmV-5xVoinBqltdbs566g.png" /></figure><p>This is the chart for easy follow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EWOrTOE09ptYrS4G" /></figure><p>We can have some main comments on this chart</p><ul><li>Channel is not good in terms of performance. Read or write don’t matter here, because we use the same channel lock mechanism. Note that channel is a powerful tool in complex scenarios. Speed is not its strength</li><li>Atomic is a winner compared to Mutex for basic scenarios (especially in case the r/w rate is high). Atomic operations leverage special CPU instructions(here are load and store) =&gt; That is why they are so fast and efficient. But we need to pay attention to what atomic operations guarantee here. It is a sequential consistency memory model, when you store at goroutine 1, there is no guarantee that goroutine 2 can load the new value in a <strong>happens-before relationship </strong>manner.</li><li>Go RW Mutex uses basically the atomic CAS. From the benchmark result, it seems like there is no difference in performance in terms of using Lock/RLock. Note that in complex scenarios, the cost is in the logic after you lock for updating the data (or do some logic)</li></ul><p><strong>Note:</strong> It is a benchmark result for a simple scenario to have a basic understanding. For complex scenarios, caching a big object, or critical block of code, there are many things that need to be considered as well. (avoid garbage collection, for example)</p><p><strong>IV/ Conclusion</strong></p><p>I quote this from <a href="https://go.dev/ref/mem#synchronization">Go Memory Model</a></p><blockquote>If you must read the rest of this document to understand the behavior of your program, you are being too clever.</blockquote><blockquote>Don’t be clever.</blockquote><p>I don’t agree it as a software engineer. We should understand how a computer works in detail, and how an engineer’s decision is made. That kind of mindset is helpful with a lot of problems in the engineering world.</p><p><a href="https://go.dev/pkg/sync/atomic/">sync/atomic</a> is a powerful package in terms of performance. You don’t need it most of the time, but for some specific problems (at large scale), we can’t ignore it.</p><p><strong>References</strong></p><p><a href="https://research.swtch.com/mm">https://research.swtch.com/mm</a> (must read if you want to understand what is memory models)</p><p><a href="https://go101.org/article/memory-model.html">https://go101.org/article/memory-model.html</a></p><p><a href="https://go.dev/ref/mem">https://go.dev/ref/mem</a></p><p><a href="https://blogtitle.github.io/categories/concurrency/">https://blogtitle.github.io/categories/concurrency/</a></p><p><a href="https://www.youtube.com/watch?v=VmrEG-3bWyM">https://www.youtube.com/watch?v=VmrEG-3bWyM</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be36e1e36411" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TCP Connection Termination in GO]]></title>
            <link>https://medium.com/@xuan11290/tcp-connection-termination-in-go-d786ecd071f2?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d786ecd071f2</guid>
            <category><![CDATA[tcp]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[eof]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 10:41:06 GMT</pubDate>
            <atom:updated>2023-07-31T02:44:06.969Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>I/ Introduction</strong></h3><p>Recently, I met a network issue when using the TCP connection pool in GO. It is a small percentage of the total number of requests (but it happened every day)</p><pre>*** handler.go:153: [error] *** Post &quot;https://***&quot;: EOF<br>*** handler.go:153: [error] *** Post &quot;https://***&quot;: EOF</pre><p>Researching this error helped me to understand how TCP connections are handled in the underground.</p><h3>II/ Fundamental concepts</h3><p>I skip the TCP topic in general, just focusing on the termination procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/0*C2DvH6YxizN1fq3P" /></figure><blockquote>In the normal case, each side terminates its end of the connection by sending a special message with the <em>FIN (finish)</em> bit set. This message, sometimes called a <em>FIN</em>, serves as a connection termination request to the other device, while also possibly carrying data like a regular segment. The device receiving the <em>FIN</em> responds with an acknowledgment to the <em>FIN</em> to indicate that it was received. The connection as a whole is not considered terminated until both sides have finished the shutdown procedure by sending a <em>FIN</em> and receiving an <em>ACK</em>.</blockquote><blockquote>Thus, termination isn’t a three-way handshake like establishment: it is a pair of two-way handshakes. The states that the two devices in the connection move through during a normal connection shutdown are different because the device initiating the shutdown must behave differently than the one that receives the termination request. In particular, the TCP on the device receiving the initial termination request must inform its application process and wait for a signal that the process is ready to proceed. The initiating device doesn’t need to do this, since the application is what started the ball rolling in the first place.</blockquote><blockquote><strong>Key Concept: </strong>A TCP connection is normally terminated using a special procedure where each side independently closes its end of the link. It normally begins with one of the application processes signaling to its TCP layer that the session is no longer needed. That device sends a <em>FIN</em> message to tell the other device that it wants to end the connection, which is acknowledged. When the responding device is ready, it too sends a <em>FIN</em> that is acknowledged; after waiting a period of time for the <em>ACK</em> to be received, the session is closed.</blockquote><h3><strong>III/ Deep-dived problem</strong></h3><p>TCP connections are bidirectional. Each side of a TCP connection has an input queue and an output queue, for data being read or written. Data placed in the output of one side will eventually show up on the input of the other side.</p><p>The server can never know for sure that the client on the other end of the line wasn’t about to send data at the same time that the “idle” connection was being shut down by the server. If this happens, the client sees a connection error in the middle of writing its request message.</p><p>From <a href="https://datatracker.ietf.org/doc/html/rfc7230#section-6.3.1">RFC7230</a></p><blockquote>Connections can be closed at any time, with or without intention. Implementations ought to anticipate the need to recover from asynchronous close events.</blockquote><blockquote>When an inbound connection is closed prematurely, a client MAY open a new connection and automatically retransmit an aborted sequence of requests if all of those requests have idempotent methods. A proxy MUST NOT automatically retry non-idempotent requests.</blockquote><blockquote>A user agent MUST NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied.</blockquote><p>Take a look at a simple Go client-server application (Go env: 1.20)</p><pre>package main<br><br>import (<br>  &quot;bytes&quot;<br>  &quot;fmt&quot;<br>  &quot;io&quot;<br>  &quot;log&quot;<br>  &quot;net&quot;<br>  &quot;net/http&quot;<br>  &quot;time&quot;<br>)<br><br>func main() {<br>  port := 9999<br>  idleTime := time.Second<br><br>  if err := createServer(9999, idleTime); err != nil {<br>     log.Fatalf(&quot;error creating server: %s&quot;, err)<br>  }<br><br>  client := &amp;http.Client{<br>     Timeout: 30 * time.Second,<br>     Transport: &amp;http.Transport{<br>        MaxIdleConns:          100,<br>        IdleConnTimeout:       idleTime + time.Millisecond,<br>        ExpectContinueTimeout: 1 * time.Second,<br>     },<br>  }<br>  urlString := fmt.Sprintf(&quot;http://localhost:%d/test&quot;, port)<br>  payloadString := &quot;my payload&quot;<br><br>  for {<br>     err := request(client, urlString, payloadString)<br>     if err != nil {<br>        log.Printf(&quot;request failed: %s&quot;, err)<br>     } else {<br>        log.Printf(&quot;request succeeded&quot;)<br>     }<br><br>     time.Sleep(idleTime)<br>  }<br>}<br><br>func createServer(port int, idleTime time.Duration) error {<br>  server := &amp;http.Server{<br>     Handler: http.HandlerFunc(<br>        func(w http.ResponseWriter, r *http.Request) {<br>           if _, err := w.Write([]byte(`ok!`)); err != nil {<br>              log.Printf(&quot;error writing to client: %s&quot;, err)<br>           }<br>        },<br>     ),<br>     IdleTimeout: idleTime,<br>  }<br><br>  listener, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;127.0.0.1:%d&quot;, port))<br>  if err != nil {<br>     return fmt.Errorf(&quot;error listening: %s&quot;, err)<br>  }<br><br>  go func() {<br>     if err := server.Serve(listener); err != nil {<br>        log.Printf(&quot;error serving: %s&quot;, err)<br>     }<br>     if err := listener.Close(); err != nil {<br>        log.Printf(&quot;error closing listener: %s&quot;, err)<br>     }<br>  }()<br><br>  return nil<br>}<br><br>func request(client *http.Client, urlString, payloadString string) error {<br>  payload := bytes.NewBufferString(payloadString)<br><br>  req, err := http.NewRequest(http.MethodPost, urlString, payload)<br>  if err != nil {<br>     return fmt.Errorf(&quot;error creating request: %s&quot;, err)<br>  }<br><br>  resp, err := client.Do(req)<br>  if err != nil {<br>     return fmt.Errorf(&quot;error performing request: %s&quot;, err)<br>  }<br><br>  if resp.StatusCode != http.StatusOK {<br>     body, _ := io.ReadAll(resp.Body)<br>     _ = resp.Body.Close()<br>     return fmt.Errorf(&quot;HTTP %d: %s&quot;, resp.StatusCode, body)<br>  }<br><br>  body, err := io.ReadAll(resp.Body)<br>  if err != nil {<br>     _ = resp.Body.Close()<br>     return fmt.Errorf(&quot;error reading body: %s&quot;, err)<br>  }<br><br>  if err := resp.Body.Close(); err != nil {<br>     return fmt.Errorf(&quot;error closing body: %s&quot;, err)<br>  }<br><br>  if string(body) != &quot;ok!&quot; {<br>     return fmt.Errorf(&quot;unexpected response: %s&quot;, body)<br>  }<br><br>  return nil<br>}</pre><p>Here is the output result</p><pre>*** request succeeded<br>*** request succeeded<br>*** request failed: error performing request: Post &quot;http://localhost:9999/test&quot;: EOF<br>*** request succeeded<br>*** request failed: error performing request: Post &quot;http://localhost:9999/test&quot;: read tcp 127.0.0.1:63782-&gt;127.0.0.1:9999: read: connection reset by peer<br>*** request succeeded<br>*** request succeeded<br>*** request succeeded<br>*** request failed: error performing request: Post &quot;http://localhost:9999/test&quot;: EOF<br>*** request succeeded<br>*** request failed: error performing request: Post &quot;http://localhost:9999/test&quot;: EOF</pre><p>The main point here is that</p><ul><li>We set the idle timeout connection to be similar in both the client and server.</li><li>It is POST (non-idempotent) request</li></ul><p>For the normal Tcp termination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UTrXcslJKC2oaaTQ" /></figure><p>Client (port 63804) — FIN — &gt; Server, Client (port 63804) ← ACK — Server</p><p>Client (port 63804) ← FIN — Server, Client (port 63804) —ACK →Server</p><p>For the abnormal Tcp termination:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3ky5XyNjCqszQHhD" /></figure><p><strong>On the client (port 63788), after the server sends the FIN flag (no more data returned from the server), the client still makes a POST request.<br>So the server sends an RST flag (TCP reset) to try to close the termination procedure.</strong></p><p>RST flag explanation</p><blockquote>When an unexpected TCP packet arrives at a host, that host usually responds by sending a reset packet back on the same connection. A reset packet is simply one with no payload and with the RST bit set in the TCP header flags.</blockquote><blockquote>There are a few circumstances in which a TCP packet might not be expected; the two most common are:</blockquote><blockquote>- The packet is an initial SYN packet trying to establish a connection to a server port on which no process is listening.</blockquote><blockquote><strong>- The packet arrives on a TCP connection that was previously established, but the local application already closed its socket or exited and the OS closed the socket.</strong></blockquote><h3>Conclusions</h3><p>As I mentioned before, the errors (EOF, connection reset by peer, …) happen when it is a non-idempotent request and the TCP connection is in a termination procedure.</p><p>I skip some unstable network errors here. So we have some tricks to avoid this issue:</p><ul><li>For <a href="https://www.rfc-editor.org/rfc/rfc7231#section-4.2.2">idempotent methods</a>, Go <a href="https://pkg.go.dev/net/http"><strong>net/http</strong></a> lib will retry it underground. For non-idempotent methods, the lib offers an option by using headers: <a href="https://github.com/golang/go/blob/master/src/net/http/request.go#L1428">“<strong>Idempotency-Key</strong>” or “<strong>X-Idempotency-Key</strong>”</a>. But you need to understand the side effect of auto-retrying a request from the client. You need to have an idempotent mechanism on the server side as well, but in general, it is unsafe.</li></ul><pre>func (r *Request) isReplayable() bool {<br> if r.Body == nil || r.Body == NoBody || r.GetBody != nil {<br>  switch valueOrDefault(r.Method, &quot;GET&quot;) {<br>  case &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;TRACE&quot;:<br>   return true<br>  }<br>  // The Idempotency-Key, while non-standard, is widely used to<br>  // mean a POST or other request is idempotent. See<br>  // https://golang.org/issue/19943#issuecomment-421092421<br>  if r.Header.has(&quot;Idempotency-Key&quot;) || r.Header.has(&quot;X-Idempotency-Key&quot;) {<br>   return true<br>  }<br> }<br> return false<br>}</pre><ul><li>Don’t use the same idle timeout config between client and server. For example, you can set server timeout to 10s, and client timeout to 8s. 2s is a buffer time for the TCP termination procedure.</li><li>Don’t use TCP keep-alive. Close TCP connection right after using, but it is a huge performance downgrade. (we can use <a href="https://github.com/golang/go/blob/master/src/net/http/request.go#L226">request.Close=true</a>)</li></ul><h4>References</h4><p><a href="http://www.tcpipguide.com/free/t_TCPConnectionTermination-2.htm">http://www.tcpipguide.com/free/t_TCPConnectionTermination-2.htm</a></p><p><a href="https://www.oreilly.com/library/view/http-the-definitive/1565925092/ch04s07.html">https://www.oreilly.com/library/view/http-the-definitive/1565925092/ch04s07.html</a></p><p><a href="https://github.com/golang/go/issues/22158">https://github.com/golang/go/issues/22158</a></p><p><a href="https://github.com/golang/go/issues/19943#issuecomment-421092421">https://github.com/golang/go/issues/19943#issuecomment-421092421</a></p><p><a href="https://www.pico.net/kb/what-is-a-tcp-reset-rst/">https://www.pico.net/kb/what-is-a-tcp-reset-rst/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d786ecd071f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Prepared Statements in GO]]></title>
            <link>https://medium.com/@xuan11290/understand-mysql-prepared-statement-1eb1bda59f7b?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eb1bda59f7b</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[prepared-statements]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mariadb]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 10:35:24 GMT</pubDate>
            <atom:updated>2023-07-20T08:47:39.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EDfrojRI7BZEqOUMUp_Emg.png" /></figure><p><strong>1/ Mysql Prepared Statement</strong></p><p>The prepared statement is used to execute the same statements repeatedly with high efficiency. It takes advantage of the client/server <a href="https://mariadb.com/kb/en/3-binary-protocol-prepared-statements/">binary protocol</a></p><ul><li>Less overhead for parsing the statement each time it is executed</li><li>Protection against SQL injection attacks</li></ul><p>SQL syntax for prepared statements is based on three steps:</p><pre>PREPARE stmt_name FROM preparable_stmt</pre><p>A statement template is sent to the database server. The server prepares a statement for execution.</p><pre>EXECUTE stmt_name [USING @var_name [, @var_name] …]</pre><p>The client binds parameter values and sends them to the server. The server creates a statement from the statement template and the bound values to execute it.</p><pre>{DEALLOCATE | DROP} PREPARE stmt_name</pre><p>It is the last and optional step, which is used to release the prepared statement.</p><p><strong>2/ Prepared statement in GO</strong></p><p><a href="https://pkg.go.dev/database/sql"><em>database/sql</em></a> is a standard library package responsible for connectivity and interaction with databases.</p><p>Using a prepared statement with this library needs to <a href="https://github.com/VividCortex/go-database-sql-tutorial/blob/gh-pages/prepared.md">pay attention</a>. So the main point here is that if the statements aren’t reused enough and security issues are handled in other ways, we may have some performance issues</p><ul><li>Double the roundtrip times. (need 2 separating steps: prepare and execute)</li><li>A re-preparing statement happens many times.</li></ul><p>For the number of roundtrips, go-SQL-driver introduces a variable named `<a href="https://github.com/go-sql-driver/mysql#interpolateparams">interpolateParams</a>`, which can be used to merge 2 steps: prepare &amp; execute. There is a tradeoff between performance and security in applying this.</p><p>Let’s deep dive into the point: statements are being prepared many times.</p><p>Create a table and insert 10k records into the table</p><pre>CREATE TABLE IF NOT EXISTS `test`.`requests` (<br>   `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,<br>   `client_code` VARCHAR(63) NOT NULL DEFAULT &#39;&#39;,<br>   `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,<br>   `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,<br>   PRIMARY KEY (`id`))<br>   ENGINE = InnoDB<br>   DEFAULT CHARACTER SET = utf8;</pre><p>Go database/sql package uses prepared statements when filling in parameters in SQL queries.</p><p>Creating a connection pool with 2 connections, run 2 types of queries with 10 goroutines like below</p><p>(I just remove the error handling part for easy following)</p><p><strong>For using the parameterized query:</strong></p><pre>ctx := context.TODO()<br>db, _ := sql.Open(&quot;mysql&quot;,<br>  &quot;admin:password@tcp(127.0.0.1:3306)/test?charset=utf8mb4&amp;parseTime=True&amp;loc=Local&quot;)<br>defer db.Close()<br>db.SetMaxOpenConns(2)<br><br>//stm1, _ := db.PrepareContext(ctx, &quot;select * from requests WHERE id=? and client_code=? limit 1&quot;)<br>//stm2, _ := db.PrepareContext(ctx, &quot;select * from requests WHERE id =? limit 1&quot;)<br><br>var wg sync.WaitGroup<br>for i := 0; i &lt; 10; i++ {<br>  wg.Add(1)<br>  j := i<br><br>  go func() {<br>     defer wg.Done()<br>     var r Request<br>     if rand.Intn(2) == 1 {<br>        //rows, _ := stm1.QueryContext(ctx, j, &quot;client2&quot;)<br>        rows, _ := db.QueryContext(ctx, &quot;select * from requests WHERE id=? and client_code=? limit 1&quot;, j, &quot;client2&quot;)<br>        //rows, _ := db.QueryContext(ctx, fmt.Sprintf(&quot;SELECT * FROM requests WHERE id = %d and client_code=&#39;%s&#39; limit 1&quot;, j, &quot;client2&quot;))<br>        defer rows.Close()<br>        for rows.Next() {<br>           _ = rows.Scan(&amp;r.ID, &amp;r.ClientCode, &amp;r.CreatedAt, &amp;r.UpdatedAt)<br>        }<br><br>     } else {<br>        //rows, _ := stm2.QueryContext(ctx, j)<br>        rows, _ := db.QueryContext(ctx, &quot;select * from requests WHERE id =? limit 1&quot;, j)<br>        //rows, _ := db.QueryContext(ctx, fmt.Sprintf(&quot;SELECT * FROM requests WHERE id = %d limit 1&quot;, j))<br>        defer rows.Close()<br>        for rows.Next() {<br>           _ = rows.Scan(&amp;r.ID, &amp;r.ClientCode, &amp;r.CreatedAt, &amp;r.UpdatedAt)<br>        }<br>     }<br>  }()<br>}<br>wg.Wait()</pre><p>Use Wireshark to capture the TCP connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u2W442txff_3qfuL" /></figure><p>So we can see in the image, for each query, `database/sql` needs 2 tcp connections( 1 for the preparing step, 1 for executing step) underground.</p><p>At the preparing step, the DB server will return a statement ID, then the client will use this statement ID at executing step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Amk9zlVZWprTcAng" /></figure><p>At the DB server, this statement ID will be managed per connection. 2 connections can have the same statement ID.</p><p>And the total number of statements is limited by the <a href="https://github.com/MariaDB/server/blob/10.4/sql/sql_class.cc#L4190">max_prepared_stmt_count</a> value.</p><p><strong>For using prepared statements explicitly</strong></p><p>We need to prepare 2 statements first</p><pre>stm1, _ := db.PrepareContext(ctx, &quot;select * from requests WHERE id=? and client_code=? limit 1&quot;)<br>stm2, _ := db.PrepareContext(ctx, &quot;select * from requests WHERE id =? limit 1&quot;)</pre><p>Then reuse them in executing step</p><pre>rows, _ := stm1.QueryContext(ctx, j, &quot;client2&quot;)<br>rows, _ := stm2.QueryContext(ctx, j)</pre><p>Capture TCP connections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KWOrzO0zfCmGjYGQ" /></figure><p>Each connection (in our 2 connections) will prepare a statement itself, then the statement will be reused per connection (no need to prepare anymore)</p><ul><li>A Statement is managed per connection. So if a connection wants to execute a query, it needs to prepare a statement itself.</li><li>We use a connection pool, and from <a href="https://github.com/VividCortex/go-database-sql-tutorial/blob/gh-pages/prepared.md">the document</a>, connections are not exposed directly. The connection pool will decide which connection is available to use, it will prepare statements itself, and in a specific heavy load use case, this can be a performance problem</li></ul><blockquote>This can result in apparent leaks of statements, statements being prepared and re-prepared more often than you think, and even running into server-side limits on the number of statements.</blockquote><ul><li>But in most cases, the benefit of using the prepared statement is significant (even the potential re-preparing issue). I will do a small benchmark for this later.</li></ul><p><strong>For</strong> <strong>using the raw query (not prepared):</strong></p><pre>rows, _ := db.QueryContext(ctx, fmt.Sprintf(&quot;SELECT * FROM requests WHERE id = %d and client_code=&#39;%s&#39; limit 1&quot;, j, &quot;client2&quot;))<br>rows, _ := db.QueryContext(ctx, fmt.Sprintf(&quot;SELECT * FROM requests WHERE id = %d limit 1&quot;, j))</pre><p>Capture TCP connections</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*plSxXjiZabMl3J13" /></figure><p>Each query needs 1 TCP connection for querying directly (instead of 2 steps). And in a high-concurrency application, reducing the number of connections to DB is one of the critical optimizations.</p><p>Let’s do a simple benchmark to evaluate the response time when there are a lot of concurrent queries (increase the connection pool to 20, the number of goroutines to 1000)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpTQvoftnUoTvNCirQELLw.png" /></figure><p>There is no significant difference between the raw query and the cached prepared statement (~ 120ms). But there is a huge difference with parameterized queries (~250ms). But we need to consider some factors that impacted this benchmark</p><ul><li>We just tested a simple select query, so the cost for the query parser is small, so no difference between cached prepared statements and raw query</li><li>Creating 1000 gorotine and running concurrently. So optimizing the number of connections will help to have a better result. <strong>Parameterized queries </strong>have ~ 2 times of tcp connections to db, so that is why it has the worst performance</li><li>We ignore db cache for the `select` query (using the same select query many times)</li></ul><p><strong>GORM</strong></p><p>It is the same mechanism as <a href="https://gorm.io/docs/index.html">GORM</a>. In Gorm, we have the same 3 query types<br><strong>Parameterized query</strong></p><pre>_ = dbStore.DB.WithContext(ctx).Where(&quot;client_code=? and id=?&quot;, &quot;client2&quot;, localI).Limit(1).Find(request)</pre><p><strong>Raw Query(no prepared)</strong></p><pre>_ = dbStore.DB.WithContext(ctx).Raw(fmt.Sprintf(&quot;SELECT * FROM requests WHERE id = %d and client_code=&#39;%s&#39; limit 1&quot;, localI, &quot;client2&quot;)).Scan(request)</pre><p><strong>Cached prepared statements</strong></p><p>Use with <a href="https://gorm.io/docs/performance.html#Caches-Prepared-Statement">gorm config</a></p><pre>dbGorm, _ := gorm.Open(mysql.Open(dsn), &amp;gorm.Config{PrepareStmt: true})</pre><p>Gorm will cache statements itself. Gorm will scan the statement from its cache layer and execute it (like the way we reuse statements in the previous example with database/sql)</p><p>For POSTGRES, gorm enables a prepared statement cache <a href="https://gorm.io/docs/connecting_to_the_database.html#PostgreSQL">by default</a>.</p><p><strong>Conclusion</strong></p><p>Understanding how prepared statements work will help to have better decisions. Through this example, I hope to clarify the performance of using a prepared statement query.</p><p>The tradeoff between security and performance should be considered carefully in specific use cases.</p><p><strong>P/S</strong>: I have met a MariaDB bug recently. It also relates to prepared statements.</p><p>It happens in Mariadb version 10.3.4 (fixed from 10.3.5), I met this issue right after its release so there is no available information, and it is hard to detect the issue at that time (finding the amazing number 1000).</p><p>It is about executing a prepared statement with <a href="https://jira.mariadb.org/browse/MDEV-27937">? in IN list</a> (when there are a lot of parameters, more than in_predicate_conversion_threshold=1000 by default)</p><p>It is not straightforward when facing the issue at that time. Researching the issue and the prepared statement help me to use RDBMS better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eb1bda59f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understand MySQL Query Optimizer in preferring ordered indexes]]></title>
            <link>https://medium.com/@xuan11290/understand-mysql-query-optimizer-in-preferring-order-index-e974c07c77bc?source=rss-4898d0bb4f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e974c07c77bc</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[optimizer]]></category>
            <category><![CDATA[mariadb]]></category>
            <category><![CDATA[indexing]]></category>
            <dc:creator><![CDATA[Xuan]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 11:17:20 GMT</pubDate>
            <atom:updated>2023-07-25T10:28:27.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*jytz_X4_nIxl3MPmV_Wnew.png" /></figure><h3><strong>I/ Introduction</strong></h3><p>The Mysql index is an important topic. Understanding how it works is a critical point in using them effectively.</p><p>Sometimes, MySQL optimizers don’t use the index we want. They try to use a primary index that causes a significant performance downgrade. Through an example, I hope that we can understand that kind of decision.</p><h3><strong>II/ Fundamental concepts</strong></h3><h4>1. InnoDB statistics</h4><ul><li><a href="https://mariadb.com/kb/en/xtradbinnodb-server-system-variables/#innodb_stats_persistent">innodb_stats_persistent</a> — when set (the default) enables InnoDB persistent statistics.</li><li><a href="https://mariadb.com/kb/en/xtradbinnodb-server-system-variables/#innodb_stats_auto_recalc">innodb_stats_auto_recalc</a> — when set (the default), persistent statistics are automatically recalculated when the table changes significantly (more than 10% of the rows)</li><li><a href="https://mariadb.com/kb/en/xtradbinnodb-server-system-variables/#innodb_stats_persistent_sample_pages">innodb_stats_persistent_sample_pages</a> — Number of index pages sampled (default 20) when estimating cardinality and statistics for indexed columns. Increasing this value will increase index statistics accuracy, but use more I/O resources when running <a href="https://mariadb.com/kb/en/analyze-table/">ANALYZE TABLE</a>.</li></ul><h4>2. Index cardinality</h4><p>An estimate of the number of unique values in the index. CARDINALITY is counted based on statistics stored as integers, so the value is not necessarily exact even for small tables. The higher the cardinality, the greater the chance that MySQL uses the index.</p><h4>3. File sort</h4><p>Filesort is the catch-all algorithm for producing sorted results for ORDER-BY or GROUP-BY queries</p><ul><li>Read the rows that match the WHERE clause.</li><li>For each row, record a tuple of values consisting of the sort key value and the additional fields referenced by the query.</li><li>When the sort buffer becomes full, sort the tuples by sort key value in memory and write it to a temporary file.</li><li>After merge-sorting the temporary file, retrieve the rows in sorted order, read the required columns directly from the sorted tuples</li></ul><h3>III/ How does the query optimizer prefer ordering index</h3><p>Env: Mariadb v10.4</p><p>The <a href="https://dev.mysql.com/doc/refman/8.0/en/controlling-optimizer.html">Query Optimizer</a> is a part of query execution that chooses the query plan. A <a href="https://dev.mysql.com/doc/refman/8.0/en/execution-plan-information.html">Query Execution Plan</a> is the way MySQL chooses to execute a specific query. It includes index choices, join types, table query order, temporary table usage, and sorting type …</p><p>In the case of a query having an ORDER BY or GROUP BY with a LIMIT clause, the optimizer tries to use an ordered index instead of an unordered index, a filesort, or some other optimization. This optimization is performed by default whenever the optimizer determines that using it would allow for faster execution of the query.</p><p>Through an example, we can understand exactly when the query optimizer chooses the ordered index.</p><p><strong>Show table info<br></strong><em>(I.1)</em></p><pre>mysql&gt; desc requests;<br>+-------------+---------------------+------+-----+---------------------+-------------------------------+<br>| Field       | Type                | Null | Key | Default             | Extra                         |<br>+-------------+---------------------+------+-----+---------------------+-------------------------------+<br>| id          | bigint(20) unsigned | NO   | PRI | NULL                | auto_increment                |<br>| client_code | varchar(63)         | NO   | MUL |                     |                               |<br>| created_at  | timestamp           | NO   |     | current_timestamp() |                               |<br>| updated_at  | timestamp           | NO   |     | current_timestamp() | on update current_timestamp() |<br>+-------------+---------------------+------+-----+---------------------+-------------------------------+<br>4 rows in set (0.00 sec)<br><br>mysql&gt; select count(*),client_code from requests group by client_code;<br>+----------+-------------+<br>| count(*) | client_code |<br>+----------+-------------+<br>|    20000 | client1     |<br>|    80000 | client2     |<br>+----------+-------------+<br>2 rows in set (0.04 sec)<br><br>mysql&gt; show index from requests;<br>+----------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+<br>| Table    | Non_unique | Key_name                   | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |<br>+----------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+<br>| requests |          0 | PRIMARY                    |            1 | id          | A         |      100255 |     NULL | NULL   |      | BTREE      |         |               |<br>| requests |          1 | idx_client_code_created_at |            1 | client_code | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |<br>| requests |          1 | idx_client_code_created_at |            2 | created_at  | A         |      100255 |     NULL | NULL   |      | BTREE      |         |               |<br>+----------+------------+----------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+<br>3 rows in set (0.00 sec)</pre><p>We have 100k records in the table `requests`. The number of records of the client1 is 20k, and the client2 is 80k.</p><p>2 indexes in the table: primary index (id), ref_index(client_code, created_at)</p><p><strong>Query example</strong>:<br><em>(I.2)</em></p><pre>mysql&gt; explain select * from requests where client_code=&#39;client1&#39; and created_at&gt;&#39;2023-07-10&#39; order by id asc limit 1;<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>| id   | select_type | table    | type  | possible_keys              | key                        | key_len | ref  | rows | Extra                                 |<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>|    1 | SIMPLE      | requests | range | idx_client_code_created_at | idx_client_code_created_at | 195     | NULL | 88   | Using index condition; Using filesort |<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>1 row in set (0.01 sec)<br><br>mysql&gt; select count(*) from requests where client_code=&#39;client1&#39; and created_at&gt;&#39;2023-07-10&#39;;<br>+----------+<br>| count(*) |<br>+----------+<br>|       88 |<br>+----------+<br>1 row in set (0.00 sec)<br><br>mysql&gt; explain select * from requests where client_code=&#39;client2&#39; and created_at&gt;&#39;2023-07-10&#39; order by id asc limit 1;<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>| id   | select_type | table    | type  | possible_keys              | key     | key_len | ref  | rows | Extra       |<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>|    1 | SIMPLE      | requests | index | idx_client_code_created_at | PRIMARY | 8       | NULL | 284  | Using where |<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>1 row in set (0.00 sec)<br><br>mysql&gt; select count(*) from requests where client_code=&#39;client2&#39; and created_at&gt;&#39;2023-07-10&#39;;<br>+----------+<br>| count(*) |<br>+----------+<br>|      352 |<br>+----------+<br>1 row in set (0.00 sec)</pre><p>For the same kind of query, the query optimizer chooses the primary index for the <strong>client2</strong>, but ref_index (client_code, created_at) for the <strong>client1</strong>.</p><p>Notice the <strong>rows</strong> column. Here is the explanation for this field</p><blockquote>The rows column indicates the number of rows MySQL believes it must examine to execute the query. For InnoDB tables, this number is an estimate, and may not always be exact.</blockquote><p>Let&#39;s deep dive into this decision.</p><p><strong>Analysis:</strong></p><p>We need to enable the optimizer debug trace to understand what happened here.</p><pre># Turn tracing on (it&#39;s off by default):<br>SET optimizer_trace=&quot;enabled=on&quot;;<br># Run query<br>SELECT …;<br># See the trace of the query<br>SELECT * FROM INFORMATION_SCHEMA.OPTIMIZER_TRACE;</pre><p>Here is the result (I just extract the relevant information for easier follow)</p><p>For the <strong>client1</strong> query</p><pre>{<br>            &quot;reconsidering_access_paths_for_index_ordering&quot;: {<br>              &quot;clause&quot;: &quot;ORDER BY&quot;,<br>              &quot;fanout&quot;: 1,<br>              &quot;read_time&quot;: 112.47,<br>              &quot;table&quot;: &quot;requests&quot;,<br>              <strong>&quot;rows_estimation&quot;: 88,</strong><br>              &quot;possible_keys&quot;: [<br>                {<br>                  &quot;index&quot;: &quot;PRIMARY&quot;,<br>                  &quot;can_resolve_order&quot;: true,<br>                  <strong>&quot;updated_limit&quot;: 1139,</strong><br>                  &quot;index_scan_time&quot;: 1139,<br>                  &quot;usable&quot;: false,<br>                  &quot;cause&quot;: &quot;cost&quot;<br>                },<br>                {<br>                  &quot;index&quot;: &quot;idx_client_code_created_at&quot;,<br>                  &quot;can_resolve_order&quot;: false,<br>                  &quot;cause&quot;: &quot;order can not be resolved by key&quot;<br>                }<br>              ]<br>            }<br>          }</pre><p>For the <strong>client2</strong> query</p><pre>{<br>            &quot;reconsidering_access_paths_for_index_ordering&quot;: {<br>              &quot;clause&quot;: &quot;ORDER BY&quot;,<br>              &quot;fanout&quot;: 1,<br>              &quot;read_time&quot;: 447.12,<br>              &quot;table&quot;: &quot;requests&quot;,<br>              <strong>&quot;rows_estimation&quot;: 352,</strong><br>              &quot;possible_keys&quot;: [<br>                {<br>                  &quot;index&quot;: &quot;PRIMARY&quot;,<br>                  &quot;can_resolve_order&quot;: true,<br>                  <strong>&quot;updated_limit&quot;: 284,</strong><br>                  &quot;index_scan_time&quot;: 284,<br>                  &quot;records&quot;: 100255,<br>                  &quot;chosen&quot;: true<br>                },<br>                {<br>                  &quot;index&quot;: &quot;idx_client_code_created_at&quot;,<br>                  &quot;can_resolve_order&quot;: false,<br>                  &quot;cause&quot;: &quot;order can not be resolved by key&quot;<br>                }<br>              ]<br>            }<br>          }</pre><p>There is a logic called <a href="https://github.com/MariaDB/server/blob/10.4/sql/sql_select.cc#L28972">reconsidering_access_paths_for_index_ordering</a>, this logic will decide if it is better to choose an ordered index instead.</p><h4>1/ Scanning ref_index</h4><p>The query optimizer hasn’t used the cardinality statistics for rows estimation, it has already scanned the b-tree index ref_index(client_code, created_at) to have the exact number: <em>rows_estimation.</em></p><p>In the image (I.2)</p><p>There are 88 rows that satisfied the condition (client_code= ‘client1’, createad_at&gt; ‘2023–07–10’), and 352 rows that satisfied the condition (client_code= ‘client2’, createad_at&gt; ‘2023–07–10’)</p><p>It matches the information in the optimizer trace debug.</p><h4>2/ Pessimistic calculation for unordered index, Optimistic calculation for ordered index</h4><p>Because we used ‘<strong><em>order by id limit 1’</em></strong> in the query, if the optimizer uses the primary key index (id), it doesn’t need an extra step (file sort) to sort data as using the ref_index(client_code, created_at)</p><p>That is the reason why the query optimizer prefers using ordered indexes (here is the primary key index)</p><p>Let&#39;s deep dive into the case <strong>client2</strong> where the query optimizer decides to use the primary key index.</p><p>- If using ref_index(client_code, created_at), we need to sort 352 rows to have the record we want</p><p>How does the query optimizer estimate the optimistic calculation?</p><p>We have 100k records in the table ‘<strong>requests</strong>’. Suppose that 352 records have been distributed evenly in the 100k records. So for each 100k/352 ~ 284 consecutive records, we can have one of them (352 records).</p><p>So the optimistic point here is that: We only need to find 1 record, so scan 284 consecutive record blocks in 100k records (284 first or last records, depending on the ASC|DESC), and we will have the result.</p><p>That is why we see in the optimizer debug, <strong><em>updated_limit: 1139~100255/88 (client1), “updated_limit”: 284~100255/352(client2)</em></strong><em> </em>(The optimizer use the statistics for total records)</p><p>To the <strong>client2</strong>, when we increase the limit args to 2.</p><p>- If using the primary index, the optimizer will think it must examine 2*100255/352 ~ 569</p><p>- If using ref index (client_code, created_at), the optimizer still need to examine 352 records &lt; 569</p><p>That is why the optimizer will use ref_index for this case.</p><p><em>(I.3)</em></p><pre>mysql&gt; explain select * from requests where client_code=&#39;client2&#39; and created_at&gt;&#39;2023-07-10&#39; order by id asc limit 1;<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>| id   | select_type | table    | type  | possible_keys              | key     | key_len | ref  | rows | Extra       |<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>|    1 | SIMPLE      | requests | index | idx_client_code_created_at | PRIMARY | 8       | NULL | 284  | Using where |<br>+------+-------------+----------+-------+----------------------------+---------+---------+------+------+-------------+<br>1 row in set (0.01 sec)<br><br>mysql&gt; explain select * from requests where client_code=&#39;client2&#39; and created_at&gt;&#39;2023-07-10&#39; order by id asc limit 2;<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>| id   | select_type | table    | type  | possible_keys              | key                        | key_len | ref  | rows | Extra                                 |<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>|    1 | SIMPLE      | requests | range | idx_client_code_created_at | idx_client_code_created_at | 195     | NULL | 352  | Using index condition; Using filesort |<br>+------+-------------+----------+-------+----------------------------+----------------------------+---------+------+------+---------------------------------------+<br>1 row in set (0.00 sec)</pre><p>Optimizer debug trace</p><pre>{<br>            &quot;reconsidering_access_paths_for_index_ordering&quot;: {<br>              &quot;clause&quot;: &quot;ORDER BY&quot;,<br>              &quot;fanout&quot;: 1,<br>              &quot;read_time&quot;: 447.12,<br>              &quot;table&quot;: &quot;requests&quot;,<br>              <strong>&quot;rows_estimation&quot;: 352,</strong><br>              &quot;possible_keys&quot;: [<br>                {<br>                  &quot;index&quot;: &quot;PRIMARY&quot;,<br>                  &quot;can_resolve_order&quot;: true,<br>                  <strong>&quot;updated_limit&quot;: 569,</strong><br>                  &quot;index_scan_time&quot;: 569,<br>                  &quot;usable&quot;: false,<br>                  &quot;cause&quot;: &quot;cost&quot;<br>                },<br>                {<br>                  &quot;index&quot;: &quot;idx_client_code_created_at&quot;,<br>                  &quot;can_resolve_order&quot;: false,<br>                  &quot;cause&quot;: &quot;order can not be resolved by key&quot;<br>                }<br>              ]<br>            }<br>          }</pre><p>And if the primary key is a selected index, the painful point here is that if there is no record satisfying the where condition, it will be a full scan table search -&gt; Performance and a huge resource consumption potential here.</p><h3>Conclusion</h3><p>- For a query having an ORDER BY or GROUP BY with a LIMIT clause, notice this issue. Understanding your query and your dataset help to have a better query. If you can’t avoid that, `<strong><em>Force index</em></strong>` may be an acceptable choice.</p><p>- From <a href="https://dev.mysql.com/doc/refman/8.0/en/switchable-optimizations.html#optflag_prefer-ordering-index">MySQL 8.0.21</a>, we can disable this optimization by turning off the flag `<a href="https://dev.mysql.com/doc/refman/8.0/en/switchable-optimizations.html#optflag_prefer-ordering-index">prefer_ordering_index</a>`, but you should understand what you do. For MariaDB, it is still existing.</p><p>References</p><p><a href="https://jira.percona.com/browse/PS-4935">https://jira.percona.com/browse/PS-4935</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e974c07c77bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>