<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Sandeep</title>
    <description>The latest articles on Forem by Sandeep (@sandeepkumardev).</description>
    <link>https://forem.com/sandeepkumardev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F631857%2Ff5ff9c73-2d30-49cb-955e-b53d2748ba3b.png</url>
      <title>Forem: Sandeep</title>
      <link>https://forem.com/sandeepkumardev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/sandeepkumardev"/>
    <language>en</language>
    <item>
      <title>Dead Tuples in PostgreSQL.</title>
      <dc:creator>Sandeep</dc:creator>
      <pubDate>Sun, 04 Sep 2022 15:13:36 +0000</pubDate>
      <link>https://forem.com/sandeepkumardev/how-to-handle-dead-tuples-in-postgresql-54m1</link>
      <guid>https://forem.com/sandeepkumardev/how-to-handle-dead-tuples-in-postgresql-54m1</guid>
      <description>&lt;p&gt;Today we are going to learn about Dead Tuples in PostgreSQL. As we know PostgreSQL is based on MVCC Architecture.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;MVCC is a &lt;code&gt;Multi Version Concurrency Control&lt;/code&gt; basically "A single rows has multiple versions." &lt;br&gt;
E.g, If a user insert a record of a Person whose AGE is 21. Now, he update the record with AGE 22, so what PostgreSQL does here, PostgreSQL stored those two records with the different versions.&lt;br&gt;
&lt;code&gt;Old version: Age = 21&lt;/code&gt;&lt;br&gt;
&lt;code&gt;New version: Age = 22&lt;/code&gt;&lt;br&gt;
By default user can only select the new version of the record, and old version marked as an &lt;code&gt;unused&lt;/code&gt; record. &lt;br&gt;
That types of record called &lt;code&gt;Dead Tuple&lt;/code&gt; or &lt;code&gt;Dead Row&lt;/code&gt;. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;How to find Live Tuples or Dead Tuples using &lt;code&gt;pg_stat_user_tables&lt;/code&gt;. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

select n_live_tup, n_dead_tup, relname from pg_stat_user_tables;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Find tuples from a specific table.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

SELECT n_live_tup, n_dead_tup, relname FROM
pg_stat_user_tables where relname = 'users';


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;using Alias &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

SELECT relname AS Table_Name, n_live_tup AS Live_Tuples,
n_dead_tup AS Dead_Tuples FROM
pg_stat_user_tables where relname = 'users';


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;SQL Result:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fsandeepkumardev%2Fimage%2Fupload%2Fv1662293261%2Fdead_tuples.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fres.cloudinary.com%2Fsandeepkumardev%2Fimage%2Fupload%2Fv1662293261%2Fdead_tuples.png" alt="Dead Tuples"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;How to avoid to create Dead Tuple while Inserting the duplicate data.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If a table have some unique constraint and a user trying to Insert the same data again, PostgreSQL will return an error &amp;gt; &lt;br&gt;
&lt;code&gt;Uniqueness violation. duplicate key value violates unique constraint&lt;/code&gt;. We can avoid this by using &lt;code&gt;ON CONFLICT DO NOTHING&lt;/code&gt; clause. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

INSERT INTO users VALUES ('name', 'email@gmail.com')
ON CONFLICT DO NOTHING;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It'll return &lt;code&gt;INSERT 0 0&lt;/code&gt; indicates that nothing was inserted in the table, the query didn't error out. In the case of &lt;code&gt;ON CONFLICT DO NOTHING&lt;/code&gt; no dead tuples are generated because of the pre-check.&lt;/p&gt;

&lt;p&gt;How to delete Dead Tuples using VACUUM - &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

VACUUM users;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It'll free up the space within the users table and only users table can use this space. If you want to use this free space by system then this command should be run. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

VACUUM FULL users;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://www.postgresql.org/docs/current/sql-vacuum.html#:~:text=VACUUM%20reclaims%20storage%20occupied%20by,especially%20on%20frequently%2Dupdated%20tables." rel="noopener noreferrer"&gt;Read More&lt;/a&gt; about VACUUM.&lt;/p&gt;

&lt;p&gt;Thank you &amp;lt;👨‍💻/&amp;gt; &lt;/p&gt;

</description>
      <category>postgres</category>
      <category>deadtuples</category>
      <category>vacuum</category>
    </item>
    <item>
      <title>Fix the CORS -  and How the Access-Control-Allow-Origin Header Works</title>
      <dc:creator>Sandeep</dc:creator>
      <pubDate>Mon, 05 Jul 2021 08:42:04 +0000</pubDate>
      <link>https://forem.com/sandeepkumardev/fix-the-cors-and-how-the-access-control-allow-origin-header-works-17el</link>
      <guid>https://forem.com/sandeepkumardev/fix-the-cors-and-how-the-access-control-allow-origin-header-works-17el</guid>
      <description>&lt;h3&gt;
  
  
  Why was the CORS error there in the first place?
&lt;/h3&gt;

&lt;p&gt;The error stems from a security mechanism that browsers implement called the &lt;strong&gt;same-origin policy&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The same-origin policy fights one of the most common cyber attacks out there: &lt;strong&gt;cross-site request forgery&lt;/strong&gt;. In this maneuver, a malicious website attempts to take advantage of the browser’s cookie storage system.&lt;/p&gt;

&lt;p&gt;For every HTTP request to a domain, the browser attaches any HTTP cookies associated with that domain. This is especially useful for authentication, and setting sessions. For instance, it’s feasible that you would sign into a web app like facebook-clone.com. In this case, your browser would store a relevant session cookie for the facebook-clone.com. And this is great! The session cookie gets stored. And every time you re-visit the facebook-clone.com tab, and click around the app, you don’t have to sign in again. Instead, the API will recognize the stored session cookie upon further HTTP requests.&lt;/p&gt;

&lt;p&gt;The only trouble is that the browser automatically includes any relevant cookies stored for a domain when another request is made to that exact domain. Therefore, a scenario like this can happen. Say you clicked on a particularly trick popup add, opening evil-site.com.&lt;/p&gt;

&lt;p&gt;The evil site also has the ability send a request to facebook-clone.com/api. Since the request is going to the facebook-clone.com domain, the browser includes the relevant cookies. Evil-site sends the session cookie, and gains authenticated access to facebook-clone. Your account has been successfully hacked with a cross-site request forgery attack.&lt;br&gt;
Luckily, in this situation, like a hawk ready to strike, the browser will step in and prevent the malicious code from making an API request like this. It will stop evil-site and say “Blocked by the same-origin policy. 🕶️”&lt;/p&gt;
&lt;h3&gt;
  
  
  How does the same-origin policy work under the hood?
&lt;/h3&gt;

&lt;p&gt;Under the hood, the browser checks if the origins of the web application and the server match. Above, the origins were simplified to the frontend application and backend server domains. But really, the origin is the combination of the protocol, host, and port. For example, in &lt;code&gt;https://www,facebook-clone.com&lt;/code&gt;, the protocol is &lt;code&gt;https://&lt;/code&gt;, the host is &lt;code&gt;www.facebook-clone.com&lt;/code&gt;, and the hidden port number is 443 (the port number typically used for https).&lt;/p&gt;

&lt;p&gt;To conduct the same-origin check, the browser accompanies all requests with a special request that sends the domain information receiving server. For example, for an app running on localhost:3000, the special request format looks like this:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Origin: http://localhost:3000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Reacting to this special request, the server sends back a response header. This header contains an &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; key, to specify which origins can access the server’s resources. The key will have one of two values:&lt;/p&gt;

&lt;p&gt;One: the server can be really strict, and specify that only one origin can access it:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Access-Control-Allow-Origin: http://localhost:3000&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Two: the server can let the gates go wide open, and specify the wildcard value to allow all domains to access its resources:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;Access-Control-Allow-Origin: *&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Once the browser receives this header information back, it compares the frontend domain with the &lt;code&gt;Access-Control-Allow-Origin&lt;/code&gt; value from the server. If the frontend domain does not match the value, the browser raises the red flag and blocks the API request with the CORS policy error.&lt;/p&gt;
&lt;h3&gt;
  
  
  Fix two: send your request to a proxy
&lt;/h3&gt;

&lt;p&gt;You can’t ask your users to trick their browsers by installing a plugin that applies an header in the frontend. But you can control the backend address that the web app’s API requests are going to.&lt;/p&gt;

&lt;p&gt;The cors-anywhere server is a proxy that adds CORS headers to a request. A proxy acts as an intermediary between a client and server. In this case, the cors-anywhere proxy server operates in between the frontend web app making the request, and the server that responds with data. Similar to the Allow-control-allow-origin plugin, it adds the more open &lt;code&gt;Access-Control-Allow-Origin: *&lt;/code&gt; header to the response.&lt;/p&gt;

&lt;p&gt;It works like this. Say your frontend is trying to make a GET request to:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://joke-api-strict-cors.appspot.com/jokes/random"&gt;https://joke-api-strict-cors.appspot.com/jokes/random&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But this api does not have a Access-Control-Allow-Origin value in place that permits the web application domain to access it. So instead, send your GET request to:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;https://cors-anywhere.herokuapp.com/https://joke-api-strict-cors.appspot.com/jokes/random&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The proxy server receives the &lt;code&gt;https://joke-api-strict-cors.appspot.com/jokes/random&lt;/code&gt; from the url above. Then it makes the request to get that server’s response. And finally, the proxy applies the &lt;code&gt;Access-Control-Allow-Origin: *&lt;/code&gt; to that original response.&lt;/p&gt;

&lt;p&gt;This solution is great because it works in both development and production. In summary, you’re taking advantage of the fact that the same origin policy is only implemented in browser-to-server communication. Which means it doesn’t have to be enforced in server-to-server communication!&lt;/p&gt;

&lt;p&gt;The one downside of the cors-anywhere proxy is that can often take a while to receive a response. The latency is high enough to make your applications appear a bit sluggish.&lt;/p&gt;

&lt;p&gt;This brings us to a final, even better approach.&lt;/p&gt;
&lt;h3&gt;
  
  
  Fix three: build your own proxy
&lt;/h3&gt;

&lt;p&gt;The fix I recommend in situations like this, is to build your own proxy! Exactly like the previous solution, you’re utilizing the fact that the same origin policy is not enforced within server-to-server communication. In addition, you eliminate the latency concern. You don’t need to share the cors-anywhere proxy with other consumers, and you can dedicate as many resources as you need to your own servers.&lt;/p&gt;

&lt;p&gt;Here’s some quick Node.js code that uses the express web framework to create a proxy server around the same &lt;code&gt;https://joke-api-strict-cors.appspot.com/&lt;/code&gt; from above:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) =&amp;gt; {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

app.get('/jokes/random', (req, res) =&amp;gt; {
  request(
    { url: 'https://joke-api-strict-cors.appspot.com/jokes/random' },
    (error, response, body) =&amp;gt; {
      if (error || response.statusCode !== 200) {
        return res.status(500).json({ type: 'error', message: err.message });
      }

      res.json(JSON.parse(body));
    }
  )
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () =&amp;gt; console.log(`listening on ${PORT}`));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How does this work? The proxy uses express middleware to apply a &lt;code&gt;Access-Control-Allow-Origin: *&lt;/code&gt; header to every response from the server. At its own jokes/random GET endpoint, the proxy requests a random joke from another server. The same-origin policy doesn’t step in to block the request, even though the domains are different. After all, this is a server-to-server request. Finally, the proxy creates a response to the original requester (an app on the browser) consisting of the resulting data and the middleware-applied &lt;code&gt;Access-Control-Allow-Origin: *&lt;/code&gt; header.&lt;/p&gt;

</description>
      <category>react</category>
      <category>express</category>
      <category>cors</category>
      <category>proxy</category>
    </item>
  </channel>
</rss>
