the if blocks any chance of injection because if the element is not exactly one of the values in the array it won't work so no SQL Injection can be used...
Even in that case using a parameter would be better for performance - this way, query planner needs to cache a query plan for every possible value for element.
You can't parameter column names in MySQL, parameters are transmitted separately from the query and the prepare on the query would fail so you could not set the parameters.
2 reasons this is AWS Lambda code using huge libraries very bad and they can get costly very quickly when there will be thousands of queries per second requiring larger resources or longer time to process the js code.
For context this is for a system to replace a system that currently handles more than 1.2 million requests per day, costs are a huge factor
In Lambda the bundle size will only matter on a cold start. After that it’s all warmed up and ready to go. Your cold start time may be impacted, but as long as you’re minifying your code a library is 100% okay to use.
On top of that, depending on the traffic your lambda itself can live for quite a while re-serving requests.
Library does not effect costs. Time spent executing (including loading the code), and number of executions effects cost.
And for context - I’ve written serverless systems that serve 1.2mil requests in 10 minutes…
have you ever actually built a SAM file, it compiles the node_modules from the package.json unless your implying we should manually build and include every library which also means not using layers code to make sure they are minimized which means if a critical update comes out it has to be re-done, and cold starts happen there is never a guarantee you will get a warm start.
But you also said exactly why this is a problem
Time spent executing (including loading the code), and number of executions effects cost.
This is also missing if a lambda uses to much memory and you have to increase the memory that add alot of cost very quickly
the larger the library is the more time it spends executing every function call is more time added, I have used libraries that have taken more than 30 seconds and had to rip them out and manually build a section of code to do the bit we needed to only do the basics needed so I have seen this is the real world.
And for context - I’ve written serverless systems that serve 1.2mil requests in 10 minutes…
please tell me the name of the app or product you have built that is handling 1.2mill query requests in 10 mins (that is 2.6 billion requests per year that is a top 10 web system above amazon in load with 2.41 billion) because that should be a product I know off
No, I use CDK. Much more robust, typesafe and better to write infrastructure. It comes built in with bundling using esbuild under the hood, so bundling your node_modules and minifying them is as simple as:
the larger the library is the more time it spends executing every function call is more time added
No, the larger the library, the larger the initial cold start time. Unless the library is subpar in its performance, in which case - why would you use it?
I have used libraries that have taken more than 30 seconds
Sounds like a poor choice of library.
that is 2.6 billion requests per year
That's if you extrapolate it out. Lambda is great for burst traffic. The specific app I'm talking about dealt with burst traffic. I can't say precisely what it is, but to give you an understanding - take a look in your AWS Lambda Dashboard at your account concurrency. It would be sitting at probably 1000. We've had to have our AWS TAM (Technical Account Manager) bump ours to 15k, because our concurrent lambda executions hit 12k.
I'm not a huge fan of the way your example was written, but I am even less of a fan of clowns that just slap maps and filters into their code to make unreadable, looping, inefficient, "clever" 1 liners even more so I shall give you an upvote.
The original code loop is easily visible to those who may not know how chaining 50 maps and filters over multiple data structures works under the hood. Abstracting logic so far from code monkeys (which is most programmers these days) that they cannot glance at the logic for a split second and be able to tell exactly how many times the code is looping over elements to get a baseline understanding of the efficiency is dangerous in my opinion. Verbosity and boilerplate is extremely obnoxious, but when it comes to many devs of various skill levels glancing at each others code and making changes, verbosity = descriptiveness and just writing a traditional loop is way more readable and understandable.
I guess it can be a bit harder to tell if you're not familiar with these kinds of methods. I'd argue that things like filter are clearer than implementing it manually in a for loop.
Obviously you can overdo it, same as with any construct.
I'm not just talking about clarity and readability of the end functionality. They can be easier to understand depending on the use case. I'm talking about clarity of performance at a glance. Embedded in these one liners are orders of magnitude lower performance and I blame the increase in "just spin up another instance or increase the server specs, who cares if it's performant, it's less to type and really readable!" on functions like these being overpopularized. I am not at all against them in all situations, but people are getting to the point where you'll get criticized for not using them when they shouldn't even be remotely considered as an option for "readability/ease of writing".
Here's my first attempt at making this a little more readable:
const current = new Set(statuses)
const valid = [
'bot', 'human', 'ok',
'monitored', 'suspicious', 'goodbot'
].filter(status => current.has(status))
const sqlCode = valid
.flatMap(status => [
`COUNT(
CASE \`status\`
WHEN '${status}'
THEN 1
ELSE null
END
) AS '${status}'`,
`AVG(
CASE \`status\`
WHEN '${status}'
THEN \`page_loads\`
ELSE null
END
) AS 'avgPage:${status}'`,
`AVG(
CASE \`status\`
WHEN '${status}'
THEN TIMESTAMPDIFF(
SECOND,
\`first_seen\`,
\`last_seen\`
)
ELSE null
END
) AS 'avgTime:${status}'`
])
.join(', ')
const sqlHaving = valid.join('+')
This is the true difference between avoiding repetition by factoring out the literal repeated code and avoiding repetition by using an appropriate abstraction. Maybe you could say that, if you only want the data for two statuses, that it would be more efficient to do the above, but it’s still gotta traverse the whole table
I don’t think I can put into words how this makes me feel. It’s almost unbelievable how much better and more simple this is than either solution in the image. It’s like being lost at sea and not realizing you had a radio and rations in your bag the whole time.
It honestly sometimes affects my mental health knowing that the original picture is better than most code I see on a daily basis.
so your advice is a senior should re-write the entire lambda after the junior has built it, how long is the management going to keep that staff member on with that logic, the question "why am I paying 2 people so (~£40 p/h vs ~£10 p/h) to do one lambda"? will come from a manager fairly quickly.
A senior should review it, say "don't do that, use a group by instead", and then the junior goes off and learns something. Then, next time, the junior avoids the bad practice in the first place.
The group by would not work for this query your seeing a part of its construction and guessing the rest, Same as everyone else, this is worse to do than anything read one block of a while file and know exactly what the whole file is doing.
I don't see how this code is doing anything other than a manual group by. Maybe you have other aggregate functions that would get messed up? In that case you should probably just do two queries instead of one.
If you're gonna be all "well it makes sense in context" then give us some damn context. I personally wouldn't approve this code no matter what the surrounding code looked like, there's absolutely better ways to do it than either of the snippets you provided.
2 queries instead of one are the problem (and I do personally prefer that lambdas are cheaper than DB servers because they are running Large/Long queries) but in this case, the DB is Auto Scaled and Replicated, all queries go through a connection pool manager that is in a layer. because at any time one server could vanish and the pool needs to manage that and issue a new connection that could be to a new server but it also means you have replication times the first query could hit one server in one state while the second hit a different server with a different replication state.
Most of this application goes via cache tables but this one particular part is real-time and the real-time system needs to be able to auto-scale and when doing that we have to account for replication delay.
No but its the only way a business can operate, if it's costing them more to build than they get from clients that's a loss business goes bust everyone loses there job
Sounds like BS. If you write terrible code, because it's cheaper in the short term then you will definitely shot yourself a knee cap out with a shotgun in the long run if you have to maintain the code.
No software has always been and will always be iterative, and yeah it does come back and cause problems but hopefully when the problems arise the company has enough income to front the cost of the rewrite.
Ever since the DOT COM bubble collapsed companies have to prove viability in a market to get the investment they can't do that if they have not released a product because they are still working on it. not to mention the speed of progress a better technology comes out so they have to build that in there another 18 months and a lot can change in technology in 18 months where do you draw the line?
The Company I work for started with a PHP App and UI using jQuery from the PHP codebase, then React came out and got stable so the front end moved to React and the PHP codebase got moved into being an API but the codebase was built with that possibility in mind using MVC switch the View Controller to support outputting as JSON, and then optimised the code base as needed for the React App. When Lambda was released internationally with AWS we immediately began evaluating the viability of it to replace the PHP, once stable we started the plan to move to Lambda & Node.JS and we're now implementing it, and with it, a new React app that uses the newer react systems. because god almighty has React changed in the last 3 years.
Hell even in an Open source community project it's not that easy to change stuff, look at WordPress (7 years ago they announced moving to Node.JS and are still not there), this is the difference between a small hobby project and a real production system you have to draw a line somewhere and not constantly re-architect but you must always be aware that you're going to have to re-architect at some point.
99
u/Voltra_Neo Dec 21 '22
I don't feel comfortable knowing the sql query string is built like that
20
u/[deleted] Dec 22 '22
People posting how’d they rather code it, while im sitting here unable to read those long ass lines on my phone.
3
u/Bacon_Destroyer Dec 21 '22
Missing some context so I might have misunderstood something, but I'd personally prefer a more declarative approach that avoids mutable variables.
4
u/No-Witness2349 Dec 22 '22
Here's my first attempt at making this a little more readable:
Followed by a second attempt based on /u/Helpful-Astronomer's query:
Not sure how I did, but it was fun.
1
u/[deleted] Feb 11 '23
How exactly is this optimized?
-1
u/lhsm42 Dec 22 '22
Use sets instead of lists of these element list gets too big
0
u/[deleted] Dec 21 '22
[deleted] — view deleted comment
0
u/[deleted] Dec 22 '22
[deleted] — view deleted comment